什么在c ++中使用更多的内存? 2个ints或2个函数? [英] What uses more memory in c++? An 2 ints or 2 functions?

查看:165
本文介绍了什么在c ++中使用更多的内存? 2个ints或2个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用c ++编写Nintendo DS(使用4MB的RAM)。我有一个按钮类存储数据,如x,y位置和长度。



方法1 ,类变量length,x,y和halfPoint

  Button :: Button(int setX,int setY,int setLength)
{
x = setX;
y = setY;
length = setLength;
halfPoint = length / 2;
}
//使用buttonName.halfPoint访问变量

方法2 ,类别变数length,x和y

  Button :: Button(int setX,int setY,int length )
{
x = setX;
y = setY;
length = setLength;
}

int Button :: getHalfPoint()
{
return length / 2;
}
//使用buttonName.getHalfPoint()访问变量

任何帮助谢谢。 (在实际代码中,我计算的位置要比半分复杂得多)

解决方案

p>

方法代码在内存中只存在一次,但每个对象实例存在一次成员变量。



必须计算创建的实例数(乘以 sizeof 变量),并将其与编译方法的大小进行比较(使用一个工具,例如objdump )。



您还需要比较 Button 的大小与有无额外变量,因为这是完全可能的编译器将其填充到相同的长度。


I am writing in c++ for the Nintendo DS (With 4MB of RAM). I have a button class that stores data like the x,y location and length. Which of the following would take less memory?

.

Method 1, class variables length, x, y, and halfPoint

Button::Button(int setX, int setY, int setLength)
{
    x = setX;
    y = setY;
    length = setLength;
    halfPoint = length/2;
}
//access variable with buttonName.halfPoint

Method 2, class variables length, x and y

Button::Button(int setX, int setY, int length)
{
    x = setX;
    y = setY;
    length = setLength;
}

int Button::getHalfPoint()
{
    return length/2;
}
//access variable with buttonName.getHalfPoint()

Any help is appreciated. (And in the real code I calculate a location much more complex than the half point)

解决方案

Well, that depends!

The method code exists exactly once in memory, but a member variable exists once for each object instance.

So you'll have to count the number of instances you create (multiplied by the sizeof the variable), and compare that to the size of the compiled method (using a tool like e.g. objdump).

You'll also want to compare the size of your Button with and without the extra variable, because it's entirely possible that the compiler pads it to the same length anyway.

这篇关于什么在c ++中使用更多的内存? 2个ints或2个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆