Constructor Optimization

David Leimbach kde-optimize@mail.kde.org
Tue, 21 Jan 2003 18:29:34 -0600


On Tuesday, January 21, 2003, at 01:41 PM, Benjamin Meyer wrote:

> Well a little bit more playing around and I have confirmed that gcc 
> will not
> optimize:
> obj a = b + c + d...
> to
> obj a(b);
> a += c;
> a += d;
> ....
>

This is because the compiler is not allowed to assume that '+' and '+=' 
are even related
for a class.


Postfix vs Prefix increment and decrement have a similar issue.

Be certain that you know the difference between

for (int i(0); i < Size; i++)

and

for (iterator = obj.begin(); iterator != obj.end(); iterator++);

For the first case i++ can be optimized to ++i;  because in that usage 
they
are semantically equivalent.

For the second case iterator is an object and may have defined its 
postfix ++ to
be anything... the compiler cannot legally optimize this because it 
cannot glean the
semantics from a class's operators.

So if your iterator postfix ++ is implemented orthogonally [meaning it 
copies...
increments original and returns the copy] that the compiler will 
generate code to do just that.

It means if you use postfix where you mean prefix you get a lot of 
overhead you didn't want
on class objects vs built in types.


Dave