C++ using precalculated limiters in for loops - c++

In scripting languages like PHP having a for loop like this would be a very bad idea:
string s("ABCDEFG");
int i;
for( i = 0; i < s.length(); i ++ )
{
cout << s[ i ];
}
This is an example, i'm not building a program like this. (For the guys that feel like they have to tell me why this piece of code <insert bad thing about it here>)
If this C++ example was translated to a similar PHP script the lenght of the string would be calculated every loop cycle. That would cause an enormous perfomance loss in realistic scripts.
I thought the same would apply to C++ programs but when I take a look at tutorials, several open-source libraries and other pieces of code I see that the limiter for the loop isn't precalculated.
Should I precalculate the lenght of the string s?
Why isn't the limiter always precalculated? (seen this in tutorials and examples)
Is there some sort of optimization done by the compiler?

It's all relative.
PHP is interpreted, but if s.length drops into a compiled part of the PHP interpreter, it will not be slow. But even if it is slow, what about the time spent in s[i], and what about the time spent in cout <<?
It's really easy to focus on loop overhead while getting swamped with other stuff.
Like if you wrote this in C++, and cout were writing to the console, do you know what would dominate? cout would, far and away, because that innocent-looking << operator invokes a huge pile of library code and system routines.

You should learn to justify simpler code. Try to convince yourself that sooner or later you will replace string::length implementation to more optimized one. (Even though your project will most likely miss all deadlines, and optimizing string::length will be the least of your problems.) This kind of thinking will help you focus on things that really matter, even though it's not always easy...

It depends on how the string is implemented.
On null terminated strings you have to calculate the size on every iteration.
std::string is a container and the size should be returned in O(1) time,
it depends (again) on the implementation.

The optimizer may indeed be able to optimize the call to length away if he's able to determine that its value won't change - nevertheless, you're on the safe side if you precalculate it (in many cases, however, optimization won't be possible because it's not clear to the compiler whether the condition variable could possible be changed during the loop).
In many cases, it just doesn't matter because the loop in question is not performance-relevant. Using the classic for(int i=0; i < somewhat(); ++i) is both less work to type and easier to read than for(int i=0,end=somewhat(); i < end; ++i.
Note that the C++ compiler will usually inline small functions, such as length (which would usually retrieve a precalculated length from the string object). Interpreted scripting languages usually need a dictionary lookup for a function call, so for C++ the relative overhad of the redundant check once per loop iteration is probably much smaller.

You're correct, s.length() will normally be evaluated on every loop iteration. You're better off writing:
size_t len = s.length();
for (size_t i = 0; i < len; ++i) {
...
}
Instead of the above. That said, for a loop with only a few iterations, it doesn't really matter how often the call to length() will be made.

I don't know about php but I can tell what c++ does.
Consider:
std::string s("Rajendra");
for (unsigned int i = 0; i < s.length(); i++)
{
std::cout << s[i] << std::endl;
}
If you go for looking up definition of length() (right click on length() and click on "Go To Definition") OR if you are using Visual Assist X then placing the cursor on length() and press Alt+G, you will find following:
size_type __CLR_OR_THIS_CALL length() const
{ // return length of sequence
return (_Mysize);
}
Where _Mysize is of type int, which clearly reveals that length of the string is pre-calculated and only stored value is being returned each call to length().
However,IMPO (in my personal opinion), this coding style is bad and should be best avoided. I would prefer following:
std::string s("Rajendra");
int len = s.length();
for (unsigned int i = 0; i < len; i++)
{
std::cout << s[i] << std::endl;
}
This way, you will save the overhead of calling length() function equal to length of the string number of times, which saves pushing and popping of stack frame. This can be very expensive when your string is large.
Hope that helps.

Probably.
For readability.
Sometimes. It depends on how good it is at detecting that the length will not change inside the loop.

Short answer, because there are situations where you want it called each time.
someone else's explanation: http://bytes.com/topic/c/answers/212351-loop-condition-evaluation

Well - as this is a very common scenario, most compilers will precalculate the value. Especially when looping through arrays and very common types - string might be one of them.
In addition, introducing an additional variable might destroy some other loop optimizations - it really depends on the compiler you use and might change from version to version.
Thus in some scenarious, the "optimization" could backfire.
If the code is non real "hot-spot" where every tick of performance does matter, you should write it as you did: No "manual" precalculation.
Readability is also very important when writing code! Optimizations should be done very carefully and only after intensive profiling!

std::string.length() returns fixed variable, that stores in container. It is already precalculated

In this particular case, std::string.length() is usually (but not necessarily) a constant-time operation and usually pretty efficient.
For the general case, the loop termination condition can be any expression, not just a comparison of the loop index variable (indeed, C/C++ does not recognize any particular index, just an initializer expression, a loop test expression and a loop counter expression (which just is executed every time through). The C/C++ for loop is basically syntactic sugar for a do/while compound statement.

The compiler may be able to save the result of the call and optimize away all of the extra function calls, but it may not. However, the cost of the function call will be quite low since all it has to do is return an int. On top of that, there's a good chance that it will be inlined, removing the cost of the function call altogether.
However, if you really care, you should profile your code and see whether precalculating the value makes it any faster. But it wouldn't hurt to just choose to precalculate it anyway. It won't cost you anything. Odds are, in most cases though, it doesn't matter. There are some containers - like list - where size() might not be an O(1) operation, and then precalculating would be a really good idea, but for most it probably doesn't matter much - especially if the contents of your loop are enough to overwhelm the cost of such an efficient function call. For std::string, it should be O(1), and will probably be optimized away, but you'd have to test to be sure - and of course things like the optimization level that you compile at could change the results.
It's safer to precalculate but often not necessary.

std::sting::length() returns a precalculated value. Other stl containers recalculate their size every time you call the method size()
e.g
std::list::size() recalculates the size and
std::vector::size() returns a
precalculated value
It depends on how the internal storage of the container is implemented.
std::vector is an array with capacity 2^n and std::list is an linked list.

You could precalculate the length of the string only if you KNOW the string won't ever change inside the loop.
I don't know why it is done this way in tutorials. A few guesses:
1) To get you in the habit so you don't get hosed when you are changing the value of the string inside the loop.
2) Because it is easier to understand.
Yes, the optimizer will try to improve this, if it can determine if the string won't change

Just for information, on my computer, g++ 4.4.2, with -O3, with the given piece of code, the function std::string::length() const is called 8 times.
I agree it's precalculated and the function is very likely to be inlined. Still very interesting to know when you are using your own functions/class.

If your program performs a lot of operations on strings all the time like copying strings ( with memcpy ) then it makes sense to cache the length of the string.
A good example of this I have seen in opensource code is redis.
In sds.h ( Simple Dynamic Strings ) look at sdshdr structure:
struct sdshdr {
long len;
long free;
char buf[];
};
As you can see it caches the length ( in len field ) of the character array buf and also the free space available ( in free field ) after the null character.
So the total memory allocated to buf is
len + free
This saves a realloc in case the buf needs to be modified and it fits in the space already available.

Related

Does not storing length of strings and other such values make program slower? [duplicate]

fibs is a std::vector. Using g++, I was advised to take fibs.size() out of the loop, to save computing it each time (because the vector could change)
int sum = 0;
for(int i = 0; i < fibs.size(); ++i){
if(fibs[i] % 2 == 0){
sum += fibs[i];
}
}
Surely there is some dataflow analysis in the compiler that would tell us that fibs won't change size. Is there? Or should I set some other variable to be fibs.size() and use that in the loop condition?
The compiler will likely determine that it won't change. Even if it did, size() for vectors is an O(1) operation.
Unless you know it's a problem, leave it as it is. First make it correct, then make it clear, then make it fast (if necessary).
vector::size is extremely fast anyway. It seems to me likely that the compiler will optimise this case, since it is fairly obvious that the vector is not modified and all the functions called will be inlined so the compiler can tell.
You could always look at the generated code to see if this has happened.
If you do want to change it, you need to be able to measure the time it takes before and after. That's a fair amount of work - you probably have better things to do.
size() is constant time operation, there's no penalty calling it this way. If you are concerned about performance and a more general way to go through the collection, use iterators:
int sum = 0;
for(auto it = fibs.cbegin(); it != fibs.cend(); ++it) {
if((*it) % 2 == 0){
sum += *it;
}
}
I think you are missing another, more important point here: Is this loop causing a slow-down of your application? If you do not know for sure (i.e. if you haven't profiled), you risk focusing on the wrong parts of your application.
You already have to keep thousands of things in your head when writing programs (coding guidelines, architecture (bigger picture) of your application, variable names, function names, class names, readability, etc.), you can ignore the speed of the code during your initial implementation (in at least 95% of the time). This will allow you to focus on things, which are more important and far more valuable (like correctness, readability and maintainability).
In your example the compiler can easily analyze the flow and determine that it doesn't change. In more complicated code it cannot:
for(int i = 0; i < fibs.size(); ++i){
complicated_function();
}
complicated_function can change fibs. However, since the above code involves a function call, the compiler cannot store fibs.size() in a register and hence you cannot eliminate the memory access.

Is it expensive to compute vector size in for loops, each iteration?

Does the c++ compiler take care of cases like, buildings is vector:
for (int i = 0; i < buildings.size(); i++) {}
that is, does it notice if buildings is modified in the loop or not, and then
based on that not evaluate it each iteration? Or maybe I should do this myself,
not that pretty but:
int n = buildings.size();
for (int i = 0; i < n; i++) {}
buildings.size() will likely be inlined by the compiler to directly access the private size field on the vector<T> class. So you shouldn't separate the call to size. This kind of micro-optimization is something you don't want to worry about anyway (unless you're in some really tight loop identified as a bottleneck by profiling).
Don't decide whether to go for one or the other by thinking in terms of performance; your compiler may or may not inline the call - and std::vector::size() has constant complexity, too.
What you should really consider is correctness, because the two versions will behave very differently if you add or remove elements while iterating.
If you don't modify the vector in any way in the loop, stick with the former version to avoid a little bit of state (the n variable).
If the compiler can determine that buildings isn't mutated within the loop (for example if it's a simple loop with no function calls that could have side effects) it will probably optmize the computation away. But computing the size of a vector is a single subtraction anyway which should be pretty cheap as well.
Write the code in the obvious way (size inside the loop) and only if profiling shows you that it's too slow should you consider an alternative mechanism.
I write loops like this:
for (int i = 0, maxI = buildings.size(); i < maxI; ++i)
Takes care of many issues at once: suggest max is fixed up front, no more thinking about lost performance, consolidate types. If evaluation is in the middle expression it suggests the loop changes the collection size.
Too bad language does not allow sensible use of const, else it would be const maxI.
OTOH for more and more cases I rather use some algo, lambda even allows to make it look almost like traditional code.
Assuming the size() function is an inline function for the base-template, one can also assume that it's very little overhead. It is far different from, say, strlen() in C, which can have major overhead.
It is possible that it's still faster to use int n = buildings.size(); - because the compiler can see that n is not changing inside the loop, so load it into a register and not indirectly fetch the vector size. But it's very marginal, and only really tight, highly optimized loops would need this treatment (and only after analyzing and finding that it's a benefit), since it's not ALWAYS that things work as well as you expect in that sort of regard.
Only start to manually optimize stuff like that, if it's really a performance problem. Then measure the difference. Otherwise you'll lot's of unmaintainable ugly code that's harder to debug and less productive to work with. Most leading compilers will probably optimize it away, if the size doesn't change within the loop.
But even if it's not optimized away, then it will probably be inlined (since templates are inlined by default) and cost almost nothing.

Taking vector size() out of loop condition to optimize

fibs is a std::vector. Using g++, I was advised to take fibs.size() out of the loop, to save computing it each time (because the vector could change)
int sum = 0;
for(int i = 0; i < fibs.size(); ++i){
if(fibs[i] % 2 == 0){
sum += fibs[i];
}
}
Surely there is some dataflow analysis in the compiler that would tell us that fibs won't change size. Is there? Or should I set some other variable to be fibs.size() and use that in the loop condition?
The compiler will likely determine that it won't change. Even if it did, size() for vectors is an O(1) operation.
Unless you know it's a problem, leave it as it is. First make it correct, then make it clear, then make it fast (if necessary).
vector::size is extremely fast anyway. It seems to me likely that the compiler will optimise this case, since it is fairly obvious that the vector is not modified and all the functions called will be inlined so the compiler can tell.
You could always look at the generated code to see if this has happened.
If you do want to change it, you need to be able to measure the time it takes before and after. That's a fair amount of work - you probably have better things to do.
size() is constant time operation, there's no penalty calling it this way. If you are concerned about performance and a more general way to go through the collection, use iterators:
int sum = 0;
for(auto it = fibs.cbegin(); it != fibs.cend(); ++it) {
if((*it) % 2 == 0){
sum += *it;
}
}
I think you are missing another, more important point here: Is this loop causing a slow-down of your application? If you do not know for sure (i.e. if you haven't profiled), you risk focusing on the wrong parts of your application.
You already have to keep thousands of things in your head when writing programs (coding guidelines, architecture (bigger picture) of your application, variable names, function names, class names, readability, etc.), you can ignore the speed of the code during your initial implementation (in at least 95% of the time). This will allow you to focus on things, which are more important and far more valuable (like correctness, readability and maintainability).
In your example the compiler can easily analyze the flow and determine that it doesn't change. In more complicated code it cannot:
for(int i = 0; i < fibs.size(); ++i){
complicated_function();
}
complicated_function can change fibs. However, since the above code involves a function call, the compiler cannot store fibs.size() in a register and hence you cannot eliminate the memory access.

Shall I optimize or let compiler to do that?

What is the preferred method of writing loops according to efficiency:
Way a)
/*here I'm hoping that compiler will optimize this
code and won't be calling size every time it iterates through this loop*/
for (unsigned i = firstString.size(); i < anotherString.size(), ++i)
{
//do something
}
or maybe should I do it this way:
Way b)
unsigned first = firstString.size();
unsigned second = anotherString.size();
and now I can write:
for (unsigned i = first; i < second, ++i)
{
//do something
}
the second way seems to me like worse option for two reasons: scope polluting and verbosity but it has the advantage of being sure that size() will be invoked once for each object.
Looking forward to your answers.
I usually write this code as:
/* i and size are local to the loop */
for (size_t i = firstString.size(), size = anotherString.size(); i < size; ++i) {
// do something
}
This way I do not pollute the parent scope and avoid calling anotherString.size() for each loop iteration.
It is especially useful with iterators:
for(some_generic_type<T>::forward_iterator it = container.begin(), end = container.end();
it != end; ++it) {
// do something with *it
}
Since C++ 11 the code can be shortened even more by writing a range-based for loop:
for(const auto& item : container) {
// do something with item
}
or
for(auto item : container) {
// do something with item
}
In general, let the compiler do it. Focus on the algorithmic complexity of what you're doing rather than micro-optimizations.
However, note that your two examples are not semantically identical - if the body of the loop changes the size of the second string, the two loops will not iterate the same amount of times. For that reason, the compiler might not be able to perform the specific optimization you're talking about.
I would first use the first version, simply because it looks cleaner and easier to type. Then you can profile it to see if anything needs to be more optimized.
But I highly doubt that the first version will cause a noticable performance drop. If the container implements size() like this:
inline size_t size() const
{
return _internal_data_member_representing_size;
}
then the compiler should be able to inline the function, eliding the function call. My compiler's implementation of the standard containers all do this.
How will a good compiler optimize your code? Not at all, as it can't be sure size() has any side-effects. If size() had any side effects your code relied on, they'd now be gone after a possible compiler optimization.
This kind of optimization really isn't safe from a compiler's perspective, you need to do it on your own. Doing on your own doesn't mean you need to introduce two additional local variables. Depending on your implementation of size, it might be an O(1) operation. If size is also declared inline, you'll also spare the function call, making the call to size() as good as a local member access.
Don't pre-optimize your code. If you have a performance problem, use a profiler to find it, otherwise you are wasting development time. Just write the simplest / cleanest code that you can.
This is one of those things that you should test yourself. Run the loops 10,000 or even 100,000 iterations and see what difference, if any, exists.
That should tell you everything you want to know.
My recommendation is to let inconsequential optimizations creep into your style. What I mean by this is that if you learn a more optimal way of doing something, and you cant see any disadvantages to it (as far as maintainability, readability, etc) then you might as well adopt it.
But don't become obsessed. Optimizations that sacrifice maintainability should be saved for very small sections of code that you have measured and KNOW will have a major impact on your application. When you do decide to optimize, remember that picking the right algorithm for the job is often far more important than tight code.
I'm hoping that compiler will optimize this...
You shouldn't. Anything involving
A call to an unknown function or
A call to a method that might be overridden
is hard for a C++ compiler to optimize. You might get lucky, but you can't count on it.
Nevertheless, because you find the first version simpler and easier to read and understand, you should write the code exactly the way it is shown in your simple example, with the calls to size() in the loop. You should consider the second version, where you have extra variables that pull the common call out of the loop, only if your application is too slow and if you have measurements showing that this loop is a bottleneck.
Here's how I look at it. Performance and style are both important, and you have to choose between the two.
You can try it out and see if there is a performance hit. If there is an unacceptable performance hit, then choose the second option, otherwise feel free to choose style.
You shouldn't optimize your code, unless you have a proof (obtained via profiler) that this part of code is bottleneck. Needless code optimization will only waste your time, it won't improve anything.
You can waste hours trying to improve one loop, only to get 0.001% performance increase.
If you're worried about performance - use profilers.
There's nothing really wrong with way (b) if you just want to write something that will probably be no worse than way (a), and possibly faster. It also makes it clearer that you know that the string's size will remain constant.
The compiler may or may not spot that size will remain constant; just in case, you might as well perform this optimization yourself. I'd certainly do this if I was suspicious that the code I was writing was going to be run a lot, even if I wasn't sure that it would be a big deal. It's very straightforward to do, it takes no more than 10 extra seconds thinking about it, it's very unlikely to slow things down, and, if nothing else, will almost certainly make the unoptimized build run a bit more quickly.
(Also the first variable in style (b) is unnecessary; the code for the init expression is run only once.)
How much percent of time is spent in for as opposed to // do something? (Don't guess - sample it.) If it is < 10% you probably have bigger issues elsewhere.
Everybody says "Compilers are so smart these days."
Well they're no smarter than the poor coders who write them.
You need to be smart too. Maybe the compiler can optimize it but why tempt it not to?
For the "std::size_t size()const" member function which not only is O(1) but is also declared "const" and so can be automatically pulled out of the loop by the compiler, it probably doesn't matter. That said, I wouldn't count on the compiler to remove it from the loop, and I think it is a good habit to get into to factor out the calls within the loop for cases where the function isn't constant or O(1). In addition, I think assigning the values to a variable leads to the code being more readable. I would not suggest, though, that you make any premature optimizations if it will result in the code being harder to read. Again, though, I think the following code is more readable, since there is less to read within the loop:
std::size_t firststrlen = firststr.size();
std::size_t secondstrlen = secondstr.size();
for ( std::size_t i = firststrlen; i < secondstrlen; i++ ){
// ...
}
Also, I should point out that you should use "std::size_t" instead of "unsigned", as the type of "std::size_t" can vary from one platform to another, and using "unsigned" can lead to trunctations and errors on platforms for which the type of "std::size_t" is "unsigned long" instead of "unsigned int".

Is using size() for the 2nd expression in a for construct always bad?

In the following example should I expect that values.size() will be called every time around the loop? In which case it might make sense to introduce a temporary vectorSize variable. Or should a modern compiler be able to optimize the calls away by recognising that the vector size cannot change.
double sumVector(const std::vector<double>& values) {
double sum = 0.0;
for (size_t ii = 0; ii < values.size(); ++ii) {
sum += values.at(ii);
}
}
Note that I don't care if there are more efficient methods to sum the contents of a vector, this question is just about the use of size() in a for construct.
Here's one way to do it that makes it explicit - size() is called only once.
for (size_t ii = 0, count = values.size(); ii < count; ++ii)
Edit: I've been asked to actually answer the question, so here's my best shot.
A compiler generally won't optimize a function call, because it doesn't know if it will get a different return value from one call to the next. It also won't optimize if there are operations inside the loop that it can't predict the side effects of. Inline functions might make a difference, but nothing is guaranteed. Local variables are easier for the compiler to optimize.
Some will call this premature optimization, and I agree that there are few cases where you will ever notice a speed difference. But if it doesn't make the code any harder to understand, why not just consider it a best practice and go with it? It certainly can't hurt.
P.S. I wrote this before I read Benoit's answer carefully, I believe we're in complete agreement.
It all depends on what the vector's size implementation is, how aggressive the compiler is and if it listen/uses to inline directives.
I would be more defensive and introduce the temporary as you don't have any guarantees about how efficient your compiler will be.
Of course, if this routine is called once or twice and the vector is small, it really doesn't matter.
If it will be called thousands of times, then I would use the temporary.
Some might call this premature optimization, but I would tend to disagree with that assessment.
While you are trying to optimize the code, you are not investing time or obfuscating the code in the name of performance.
I have a hard time considering what is a refactoring to be an optimization. But in the end, this is along the lines of "you say tomato, I say tomato"...
Start with size() in the 'for' construct until you need to optimize for speed.
If it is too slow, look for ways to make it faster, such as using a temporary variable to hold the result of size.
No matter the optimisation settings, putting the .size() call in the second expression will be at most as performant as outlining the .size() call before the for-loop. That is:
size_t size = values.size();
for (size_t ii = 0; ii < size; ++ii) {
sum += values.at(ii)
}
will always perform at least as well as, if not better than:
for (size_t ii = 0; ii < values.size(); ++ii) {
sum += values.at(ii);
}
In practice, it probably wont matter, since outlining the .size() call is a common compiler optimisation. However, I do find the second version easier to read.
I find this even easier, though:
double sum = std::accumulate(values.begin(), values.end(), 0);
Worth noting that even if you are dealing with millions of items the overhead is going to be negligible.
In any case this should really be written using iterator - as there may be more overhead accessing a specific example.
There is really no way that the compiler can assume that size() won't change - because it could do..
If the order of iteration isn't important then you could always write it as which is slightly more efficient.
for (int i=v.size()-1; i>=0 ;i--)
{
...
}
This isn't part of the question but why are you using at in your code in place of the subscript operator []?
The sense in at is to ensure that no operation on an invalid index occurs. However, this will never be the case in your loop since you know from your code what the indices are going to be (always assuming single-threadedness).
Even if your code contained a logical error, causing you to access an invalid element, at in this place would be useless because you don't expect the resulting exception and hence you don't treat it (or do you enclose all of your loops by try blocks?).
The use of at here is misleading because it tells the reader that you (as a programmer) don't know what values the index will have – which is obviously wrong.
I agree with Curro, this is a typical case for the use of iterators. Although this is more verbose (at least if you don't use constructs like Boost.Foreach), it is also much more expressive and safer.
Boost.Foreach would allow you to write the code as follows:
double sum = 0.0;
foreach (double d, values)
sum += d;
This operation is safe, efficient, short and readable.
It doesn't matter at all. The performance overhead of .at() is so large (it contains a conditional throw statement) that a non-optimized version will spend most of its time there. An optimizing compiler smart enough to eliminiate the conditional throw will necessarily spot that size() does not change.
I agree with Benoit. The introduction of a new variable, especially an int or even a short will have a bigger benefit that calling it each time.
It's one less thing to worry about if the loop ever gets large enough that it may impact performance.
If you hold the size of the vector in a temporary variable, you will be independent of the compiler.
My guess is, that most compilers will optimize the code in a way, that size() will be called only once. But using a temporary variable will give you a guarantee, size() will only be called once!
The size method from std::vector should be inlined by the compiler, meaning that every call to size() is replaced by its actual body (see the question Why should I ever use inline code for more information about inlining). Since in most implementations size() basically computes the difference between end() and begin() (which should be inlined too), you don't have to worry too much about loss of performance.
Moreover, if I remember correctly, some compilers are "smart" enough to detect the constness of an expression in the second part of the for construct, and generate code that evaluates the expression only once.
The compiler will not know if the value of .size() changes between calls, so it won't do any optimizations. I know you just asked about the use of .size(), but you should be using iterators anyway.
std::vector<double>::const_iterator iter = values.begin();
for(; iter != values.end(); ++iter)
{
// use the iterator here to access the value.
}
In this case, the call to .end() is similar to the problem you expose with .size(). If you know the loop does not perform any operation in the vector that invalidates the iterators, you can initialize an iterator to the .end() position prior to enter the loop and use that as your boundary.
Always write code the first time exactly as you mean it. If you are iterating over the vector from zero to size(), write it like that. Do not optimise the call to size() into a temporary variable unless you have profiled the call to be a bottleneck in your program that needs optimising.
In all likelihood, a good compiler will be able to optimise away the call to size(), particularly given that the vector is declared as const.
If you were using a container where size() was O(n) (like std::list) and not O(1) (like std::vector), you would not be iterating through that container using indices. You would be using iterators instead.
Anyway, if the body of the loop is so trivial that recalculating std::vector::size() matters, then there is probably a more efficient (but possibly platform-specific) way to do the calculation, regardless of what it is. If the body of the loop is non-trivial, recalculating std::vector::size() each time is unlikely to matter.
If you are modifying the vector (adding or removing elements) in the for loop then you should not use a temporary variable since this could lead to bugs.
If you are not modifying the vector size in the for loop then I would all the time use a temporary variable to store the size (this would make your code independant on the implementation details of vector::size.
In such cases using iterators is cleaner - in some it's even faster. There's only one call to the container - getting the iterator holding a pointer to the vector member if there are any left, or null otherwise.
Then of course for can become a while and there are no temporary variables needed at all - you can even pass an iterator to the sumVector function instead of a const reference/value.
Most, maybe even all, standard implementations of size() will be inlined by the compiler to what would be the equivalent of a temporary or at most a pointer dereference.
However, you can never be sure. Inlining is about as hidden as these things get, and 3rd party containers may have virtual function tables - which means you may not get inlined.
However, seriously, using a temporary reduces readability slightly for almost certainly no gain. Only optimise to a temporary if profiling says it is fruitful. If you make these micro optimisations everywhere, your code could become unreadable, perhaps even for yourself.
As a slight aside, no compiler would optimise size() to one of call assigning to a temporary. There is almost no guarantee of const in C++. The compiler cannot risk assuming size() will return the same value for the whole loop. For example. Another thread could change the vector in between loop iterations.