Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variables as opposed to class calls

I have recently learned that if you have a reference to a class as a function parameter, it is better practice and more efficient to store certain needed pieces of information as local variables rather than accessing the classes members every time you need them in the function.

so...

void function(const Sphere& s)
{
    //lots of calls to s.centre and s.radius
}

or

void function(const Sphere& s)
{
    Vector3 centre = s.centre; float radius = s.radius;
    //an equal amount of calls to centre and radius
}

I am told the second is better, but why? And also, where is a good place to start researching this more fully? (for dummys please!)

like image 501
Dollarslice Avatar asked Nov 27 '22 09:11

Dollarslice


1 Answers

Whoever told you this probably thought that the second version was likely to be faster.

I think this is bad advice, for two reasons:

  1. It may or may not actually be faster. This depends on the compiler, on what exactly the code is doing etc.
  2. Even if it is faster, this screams premature optimization. One should micro-optimize only after profiling the code and establishing which part of the code is the overall bottleneck.
like image 105
NPE Avatar answered Dec 13 '22 19:12

NPE