which is faster - - about function calls?

Started by
1 comment, last by Nemesis2k2 18 years, 8 months ago
OK wich Method is faster....... which Method is better...... nevermind if some of the syntax is wrong

CtheClass * mtClass = new CtheClass();

somefunction(CtheClass * pClass)
{
  if( pClass->getChair(5)->color != this->m_ColorOfTheSun)
    {
     //blahhhhhhh
    } 
  if( pClass->getChair(5)->color != this->m_ColorOfTheMoon)
    {
     //blahhhhhhh
    } 
  if( pClass->getChair(5)->color != this->m_ColorOfTheOcean)
    {
     //blahhhhhhh
    } 


}


////// OR /////////


somefunction(CtheClass * pClass)
{
  Color *theColor = pClass->getChair(5)->color ;

  if( *theColor != this->m_ColorOfTheSun)
    {
     //blahhhhhhh
    } 
  if( *theColor != this->m_ColorOfTheMoon)
    {
     //blahhhhhhh
    } 
  if( *theColor != this->m_ColorOfTheOcean)
    {
     //blahhhhhhh
    } 


}

/////////// or ///////////

somefunction(CtheClass * pClass)
{
  Color theColor = pClass->getChair(5)->color ;

  if( theColor != this->m_ColorOfTheSun)
    {
     //blahhhhhhh
    } 
  if( theColor != this->m_ColorOfTheMoon)
    {
     //blahhhhhhh
    } 
  if( theColor != this->m_ColorOfTheOcean)
    {
     //blahhhhhhh
    } 


}

so if you make reference to a pass class data quite a bit is it faster to create a copy of it to avoid function calls and look ups? ......
Advertisement
It depends.
But if you have a lot of tests or a loop AND the data you copy is small (in the case of a color it's alright) it's usually better. Your data is small so it's quick to copy and is on the stack, then you avoid a lot of pointer dereferencing and finally you avoid cache miss as you use stack data.

So I would go with the last option you propose.

The second solution might be useful if you have a long chain of pointer derefencing, and you have a massive objet (lots of members and/or dynamic allocation).
All three should be equivelant. As nothing is marked as volatile, any basic optimizing compiler will realise that the value you are using cannot change, and it will perform the lookup once, and cache the result for all of the comparisons. Don't waste your time trying to reuse results of dereferences or expressions; the compiler can figure all that out for you much quicker, and it allows you to keep your code in a form that best expresses your intent.

This topic is closed to new replies.

Advertisement