开发者

Position of reused variable for loop

What are the 开发者_如何学Cpros/cons of using Method 1 vs Method 2?

Method 1:

for ( std::vector<MyObject*>::iterator it = my_objects.begin(); it != my_objects.end(); ++it )
{
    Vector2 temp_position = (*it)->GetPosition();
    // do something...
}

Method 2:

Vector2 temp_position; // I do NOT need scope for this object outside of the loop.
for ( std::vector<MyObject*>::iterator it = my_objects.begin(); it != my_objects.end(); ++it )
{
    temp_position = (*it)->GetPosition();
    // do something...
}

Theoretically, Method 2 would have better performance than Method 1 because the temp_position variable would not need to be recreated each time through the loop. However, I remember reading that compilers will optimize them to be the same.

Method 1 is better in that temp_position does not have unnecessary scope.


If we ignore any optimizations the compiler performs, there is a concrete difference between the functions called by each version.

In Method 1, since you're creating the vector inside the loop, its constructor will be invoked once (specifically, its copy constructor), and its destructor will be invoked once, for each iteration of the loop. So the rough cost is N copy constructor calls + N destructor calls.

In Method 2, since the vector already exists in the for loop, its copy assignment operator will instead be called. So its constructor gets called once, its destructor gets called once, and its copy assignment operator is invoked N times. The rough cost is 1 copy constructor call + 1 destructor call + N copy assignment operator calls.

They end up being roughly similar in terms of how much work is done. Every call to the copy assignment operator requires allocating one array and freeing another; on the other hand, the copy constructor call allocates one array, while the destructor frees one.

I would prefer Method 1 simply because it more closely reflects what you're trying to say -- that the vector is indeed temporary, and needs not exist beyond the scope of the loop.


"Premature optimization is the root of all evil." – Etienne de Martel

Amen. However I'll misplace my halo for a second and say even though the compiler will probably optimize that loop and maybe even unwind it completely the cost of an allocation on the stack versus all the other copying and allocation you're doing there is irrelevant.

I would write that loop like below even though the compiler would probably still have it's way with it and do whatever it pleases at the end of the day.

const std::vector<MyObject*>::const_iterator end(my_objects.cend());
for (std::vector<MyObject*>::const_iterator it(my_objects.cbegin()); it != end; ++it)
{
    Vector2 temp_position((*it)->GetPosition());
    // do something...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜