Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a function that returns a constant work slower than a void function? [closed]

Simplest example to highlight the difference:

int foo()
{
   doSomething();
   return 0;
}

void bar()
{
   doSomething();
   return;
}

int main()
{
   foo();
   bar();
}

Is bar faster than foo, and why?

like image 448
Boyko Perfanov Avatar asked Jul 23 '26 06:07

Boyko Perfanov


1 Answers

This is such a micro optimization that you should never have to even consider it. Yet the usual caveats when talking about performance:

  • measure
  • measure again
  • change something
  • measure
  • make sure that you understand what you are measuring and why the change had an effect
  • change it again a bit more with the new understanding and check whether the premise holds

As of the particular case of returning a small object (something that fits in a register), the cost is going to be negligible, basically a load into a register in most architectures.

like image 112
David Rodríguez - dribeas Avatar answered Jul 25 '26 20:07

David Rodríguez - dribeas