[oclug] programming style vs performance
Olaf Baumann
olaf.baumann at pobox.com
Mon Sep 19 21:35:30 EDT 2005
Consider the following two snippets of functionally equivalent
fictional code
1)
int doSomething() {
int argOne = getArgOne();
int argTwo = createSomethingForTheSecondArgument();
int argThree = 3 * 4 * SOME_CONSTANT;
long result = doSomethingElse( argOne, argTwo, argThree);
return result;
}
2)
int doSomething() {
return result = doSomethingElse(getArgOne(),
createSomethingForTheSecondArgument(), 3 * 4 * SOME_CONSTANT);
}
Which would you prefer?
When I can, I try to write my code for the next programmer that has to
understand/modify it. Personally, I would much rather work on code
like listing 1. If needed, debugging code like listing 2 gets
difficult as there is no line or local variables whose state can be
viewed. Also, adding application logging to listing 2 would be
impossible or worse, if the methods called had side effects.
Is it possible that a compiler would produce faster code from listing 2
(having fewer /named/ local variables on the stack)? Or would any
compiler worth its salt optimize both to the same result. Not that I'm
one to fall into the trap of premature optimization, but I would like
to be aware of the possibilities.
I've tried to keep the code mostly language-independent as answers may
be language-specific and the differences between languages would be
interesting to see. For example, I would guess that if this code was
interpreted python (without any compilation stage), it would be slower
if for no other reason, there are more characters in the source to
scan.
--
Olaf
More information about the OCLUG
mailing list