Click to See Complete Forum and Search --> : Performance Cost


Sathyaish
March 16th, 2005, 08:47 AM
#include<iostream.h>

class Num
{

public:
Num(int num)
{
_num = num;
}

int GetNum()
{
return _num;
}

void DoSomething()
{
_num += GetNum(); /*Is this more expensive or the same as _num += _num? *
When calling GetNum, the function does not have to prepare
its own local stack but has to pop the value from the stack
local to the class, which is the same cost as accessing the
private variable _num directly. However, the caller has to
record its state before the call and also its return address.
Thoughts please.*/
}

private:
int _num;

};

panayotisk
March 16th, 2005, 08:59 AM
You normally make GetNum() inline to avoid the additional cost.
...Which it is, so I do not see any additional cost.
(Tip of the day: Avoid prepending the member variables with '_')

Bob Davis
March 16th, 2005, 09:27 AM
While it is very likely that GetNum() will be inlined by the compiler, there is no way to force the compiler to inline a chunk of code. Some compilers don't even support inlining of functions. If the compiler didn't inline the function, you'd have the overhead of a function call; whether this is a big deal depends on how often you call the function.

KevinHall
March 16th, 2005, 09:59 AM
Please read this FAQ (http://www.codeguru.com/forum/showthread.php?t=316185).


And panayotisk is correct about prepending variables with an underscore, because variable names with underscores can be reserved by the compiler. This is a popular practice and a reasonable suggestion I've seen in a couple places is to append an underscore at the end of the variable name -- i.e. num_

Sathyaish
March 16th, 2005, 10:07 AM
Thanks.