Programmer said:
Is this:
int x;
for (int count=0; count<200; count++)
{
x = someFunc();
anotherFunc(x);
}
more efficient than this:
for (int count=0; count<200; count++)
{
int x = someFunc();
anotherFunc(x);
}
can someone also explain why?
The second is more efficient in terms of programming time. The most
important resource to optimize is programmer time. Do not worry about which
statements are more efficient, worry about how likely they are to catch a
bug. The first version is more risky because you might find yourself using x
outside that loop, and not notice that inside the loop x gets changed.
Always give identifiers the narrowest scope possible.
After you write a big program (and all its automated tests), you can time
them to find the real performance bottleneck. Replacing algorithms will have
a much bigger effect on performance than individual integers.
In this specific case, the compiler will most likely optimize. If it puts x
on the stack, x's address reserves when the function enters, as if x had
been declared outside the loop. If it puts x into a register, then it
doesn't reserve any stack. You will never be able to time a difference
between these minor adjustments.