|
-
March 16th, 2005, 09:47 AM
#1
Performance Cost
Code:
#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;
};
-
March 16th, 2005, 09:59 AM
#2
Re: Performance Cost
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 '_')
Last edited by panayotisk; March 16th, 2005 at 10:01 AM.
Extreme situations require extreme measures
-
March 16th, 2005, 10:27 AM
#3
Re: Performance Cost
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.
-
March 16th, 2005, 10:59 AM
#4
Re: Performance Cost
Please read this FAQ.
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_
Kevin Hall
-
March 16th, 2005, 11:07 AM
#5
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|