I want to ask which piece of code is more efficient in Java? Code 1:
void f()
{
for(int i = 0 ; i < 99999;i++)
{
for(int j = 0 ; j < 99999;j++)
{
I would guess that there is absolutely no difference in efficiency for any half-decent JVM implementation.
There is one more aspect, which is very important about the two different versions:
While in variant 2 there are only two temporary objects created (i and j), variant 1 will create 100000 objects (1 x i and 999999 x j). Probably your compiler is going to optimize this, but this is something you can´t be sure of. If it doesn´t optimize it, the garbage collection will behave significantly worse.
The second is worse.
Why? Because the loop variable is scoped outside the loop. i
and j
will have a value after the loop is done. Generally that isn't what you want. The first scopes the loop variables so it's only visible within the loop.