Am Dienstag, 15. August 2006 14:37 schrieb Charles Goodwin:
> The reason to use the const is efficiency. In your version, the
> get_nr_buildings() function is going to be evaluated on every
> iteration of the for loop.
Yes, I'm well aware of that.
> If you have lots of loops like this in the=20
> code, it will be a big cause of inefficiency to have evaluated
> functions in the condition checking of your for/while loops.
I agree in principle. But, except for some obvious cases, I won't believe y=
claim without seeing profiling data (one souch obvious case would be the=20
problem with bit-depth stuff in the innermost display loop, which Erik fixe=
a while ago) (which, BTW, was supported by profiling that Erik did).
Modern compilers are far better at optimization than conventional wisdom=20
suggests. For example, "gcc -O2" will turn on -fomit-frame-pointer (creatin=
the new stack frame is the most expensive part of a function call)=20
and "gcc -O3" will turn on -finline-functions, which totally eliminates cal=
overhead for the trivial getter functions we're talking about.
Still more expensive than a constant, yes, but not expensive per se. Some=20
compilers will even recognize the "pseudo-constant" and pull it out of the=
loop of their own accord (i.e. reasonably modern gcc at -O3)
It's a question of weighing readability vs. performance, and consequently a=
matter of style.
My personal preference is to go for readability first - if I can read the=20
code, I can substitute better algorithms instead of micromanaging function=
call overheads. I'd rather change an O(n^2) approach to O(log n) than squee=
1.32% out of each loop with a trick that most compilers will do anyway.
> Erik's version is the best approach.
Yes, for suitable values of good.
Now, don't get me wrong anybody: I seriously *like* what Erik is doing, I j=
wanted to dot a single i in a great story :-)
Mit freundlichen Gr=FC=DFen,
PGP key id: A34C32F9