Frederick Gotham wrote:
Ivan Liu posted:
Hi, I wonder if it's more efficient to put variable/object delaration
outside the for/do-while loop or it doesn't matter.
If you have something like the following:
for(unsigned i = 0; i != 10; ++i)
{
MyClass obj;
}
, then the constructor is called 10 times, and the destructor is called 10
times.
If you have the following:
MyClass obj;
for(unsigned i = 0; i != 10; ++i)
{
}
, then the constructor is called once, and the destructor is called once.
I'd be quick to say that the latter would be more efficient (i.e. faster),
but then again it all depends on the classes your using, and what kind of
code the compiler makes.
Precisely: it does depend on the code in question. A relevant quote
from _Efficient C++ Programming_ by Lippman
(
http://www.awprofessional.com/articl...p=25033&rl=1):
Matrix mat;
while ( something.more() )
{
mat = something.fetch_mat();
// do something with mat ...
}
mat is set to a different Matrix class object with each iteration. The
programmer could have written
while ( something.more() )
{
Matrix mat = something.fetch_mat();
// do something with mat ...
}
but wished to avoid the construction and destruction of mat with each
loop iteration. Let's rather initialize and destroy it once prior to
and after completion of the loop, the programmer explains, not
realizing that with each iteration, the assignment requires that a
temporary be passed to fetch_mat(), where it is constructed. The
temporary is then copy assigned to mat and destructed. While placing
the definition of mat outside the loop appears more efficient, it is
actually more expensive, resulting in an additional copy assignment
operation with each loop iteration, in addition to the construction and
destruction of a temporary Matrix object.
---
Cheers! --M