Rogério Dec
Rogério Dec

Reputation: 841

Should I avoid repeated access to the same method within a loop?

I worry about the final performance of a program, at the same time, I do not want to penalize the programmer with excessive or unnecessary care in the code.

In the code below, for example, it will return the same value of getPosition method for 10000 times:

vector <int> arr;
for (int i=0; i<10000 ; i++)
    arr.push_back(i + window.getPosition().x)

In this specific case I know that window.getPosition().x will always return the same value.

To avoid a loss of performance, should I change the code to, for example:

vector <int> arr;
int x = window.getPosition().x;
for (int i=0; i<10000 ; i++)
    arr.push_back(i + x);

This always involves an additional programmer's concern.

Or is there some smart cache, where should I not worry about it?

Upvotes: 3

Views: 83

Answers (2)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275270

Maybe; this will depend on how visible the code you are calling is to the compiler (LTO or not? All visible, or separate object files?) If the compiler can prove it cannot change, the compiler will cache it for you. But seemingly innoculous things can prevent the compiler from knowing it cannot change.

The overhead here may be small, and simpler code is easier to maintain. Write the simpker, clearer, more obviously correct one. Then profile your code to find hot paths. Go over those hot paths and do that kind of optimization and reprofile to aee if it is worth it.

After decade+ of doing this, you'll get a feel for hot paths that is about 25% accurate, and you can self justify preemptively doing minor optimizations before profiling with dunning-krugar inflated confidence. Or, you know, profile.

Upvotes: 2

Thomas Cohn
Thomas Cohn

Reputation: 497

That is definitely a good idea. Even if the cost of calling the method is very small, storing a single int only costs you a few bytes and will almost definitely be quicker. You could also declare it as const to make its purpose extra clear.

Also, if efficiency is your concern, you should consider reserving memory for your vector. Right now, as you're pushing back elements into arr, you're going to have to reallocate several times. Since you're running through that loop 10000 times, it can be pretty inefficient to have to copy all that information around. Since you know you need space for 10000 elements, you should call arr.reserve(10000); before the loop.

Upvotes: 2

Related Questions