Re: Habitual optimization
Steven T. Hatton wrote:
I have long wondered about certain programming styles/strategies and how
they can impact performance.
[snip]....
const int dTick((rect.width() - 1)/settings.numXTicks);
and then writing:
int x = rect.left() + i * dTick;?
Or even `int x(rect.left());' outside the loop, and `x+=dTick'; inside the
loop?
Yes, definitely there is a gain to use the additive operation inside of
the loop.
Two in fact:
[1] You are executing an add operation instead of a multiply every
time, which is less time consuming.
[2] You are touching lesser number of variables.
Typically, on an x86 machine, the former would be:
(a) Load dTick into a temporary.
(b) Multiply i and dTick.
(c) Store the result of rect.left() in a temporary.
(d) Add the result of the above 2 temporaries.
However, the latter would be:
(a) Store the result of rect.left() in a temporary.
(b) Add the above temporary and the value of dTick.
[snip]....
One additional question I have deals with for-loops.
std::vector<Object> v;
// fill the vector
for(unsigned i(0); i<v.size(); ++i){
//do something.
}
Is it likely that an optimizer could improve performance if it could
determine that v.size() is unchanged during the loop, and thus eliminate
calls to v.size()?
Yes, definitely it would result in a performance gain.
The C++ standard specifies that the size() member function should be
constant time. It may be implemented as a difference of 2 pointers,
which boils down to difference followed by a divide with the type's
size. If these 2 operations can be eliminated(which btw involve an AGI)
then there's nothing better for speed!!!!
Regards,
-Dhruv.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]