Reputation: 5568
I was wondering if declaring a variable once (outside the loop) and then changing its value in every iteration of a loop, is faster than declaring the variable in the same line of updating its value (inside the loop), which then declares the variable every loop iteration.
On the one hand, I won't sacrifice even 1 CPU clock, but on the other, I like my code to be as short as possible.
Thank you!
Upvotes: 1
Views: 448
Reputation: 1794
In terms of performance it doesn't matter at all, so just go for whichever option has more readability for you.
Why? When the code is compiled many optimisations are applied to it to translate it into machine code. At the end a variable is just a reserved position in memory, so assume that you declare the variable inside the loop. In this case the computer would have to "reserve" a memory position every time you loop, so you would be wasting CPU clocks in each iteration of the loop. But as mentioned, many static optimisations are applied to the code, so the memory reservation would be moved out of the loop when the code is compiled.
Here you can find an explanation with a clearer example:
http://en.wikipedia.org/wiki/Loop-invariant_code_motion
But basically, modern compilers will optimise pretty much everything detectable with static code analysis.
Upvotes: 2
Reputation: 1724
Perhaps a better question to ask is why do you need this optimization?
If you are programming something so tiny with so little power that this level of optimization is needed, Java is NOT the language to use. Something like C or assembly is better suited for that.
Even in a demanding game engine, I would be reluctant to waste time with micro-optimizations like this unless it was a method that was called 60+ times a second where I could demonstrate via testing a significant impact from the optimization.
In a situation where I would be using Java, these kind of optimizations aren't worth the time they take to type.
Upvotes: 0