CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Feb 2003
    Posts
    417

    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;
    
    };

  2. #2
    Join Date
    Apr 2003
    Location
    Athens, Greece
    Posts
    1,094

    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

  3. #3
    Join Date
    Jan 2001
    Posts
    588

    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.

  4. #4
    Join Date
    Nov 2002
    Location
    Foggy California
    Posts
    1,245

    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

  5. #5
    Join Date
    Feb 2003
    Posts
    417

    Re: Performance Cost

    Thanks.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured