Suppose I have some code calling a method like vector::length() several times…does creating a temporary variable like
int length=myVector.length()
make it more efficient than calling the method several times?
This is a somewhat hypothetical question, so let’s assume calling vector::length() is the only way to get our desired result.
The cost of storing a value in a local variable is next to nothing. The cost of calling an inlined “fetch this member variable” is also next to nothing.
If, on the other hand, the object is not a vector, and
lengthis not held in a member variable, but has to be counted – say likestrlen(), then there is a great benefit of storing it in a local variable. Particularly if the string is more than a few characters long.The other problem is of course that you do something like:
And then someone else goes and edits the cdoe:
Now your code is accessing outside the valid range and may crash and burn…
As always, the devil is in the detail. If you want to know what’s fastest IN YOUR CODE, then benchmark it using your code…