does variable definition affect performance in loops?
are there any performance differences between these two blocks?
string xyz;
for (i=0; i<100; i++)
{
xyz = ...
}
for (i=0; i<100; i++)
{
string xyz = ...
}
In the 2nd for loop, does memory for xyz get deallocated / reallocated every time?
Thanks!
[329 byte] By [
rssmps] at [2007-11-11 8:07:46]

# 1 Re: does variable definition affect performance in loops?
It will be destroyed & created each time. Depending on how smart your compiler is, this may be optimized somehow to have minimal bad effects. In general, you should not do this inside a loop. An exception is a constant for a nested loop:
for(i = ...)
{
const int something = somestuff*i;
for(j = ...)
{
use(something);
}
}
This tends to be faster but you should time it and make sure.
jonnin at 2007-11-11 21:01:38 >

# 2 Re: does variable definition affect performance in loops?
The latter is of course less efficient than the first one. Not only is the memory allocated and recallocated automatically on every iteration (in this respect there's no difference between the two auto objects), but the real performance penalty is incurred by the initialization, i.e., construction of the string object. Depending on the compiler's cleverness and the implementation of std::string, the performance can vary.So it's better to create the string outside the loop and access it within the loop:
string s;
for (...)
{
s="xyz";
}
Danny at 2007-11-11 21:02:38 >
