Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which loop has better performance? Why?

People also ask

Which while loop is better and why?

Use a for loop when you know the loop should execute n times. Use a while loop for reading a file into a variable.

Which loop is the fastest loop?

For loop (forward and reverse) The traditional for loop is the fastest, so you should always use that right? Not so fast - performance is not the only thing that matters. Code Readability is usually more important, so default to the style that fits your application.

Which type of loop is best?

The for loop is probably the most common and well known type of loop in any programming language. For can be used to iterate through the elements of an array: For can also be used to perform a fixed number of iterations: By default the increment is one.

Which loop is faster in Java and why?

Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.


Limited Scope is Best

Use your second option:

for ( ... ) {
  String s = ...;
}

Scope Doesn't Affect Performance

If you disassemble code the compiled from each (with the JDK's javap tool), you will see that the loop compiles to the exact same JVM instructions in both cases. Note also that Brian R. Bondy's "Option #3" is identical to Option #1. Nothing extra is added or removed from the stack when using the tighter scope, and same data are used on the stack in both cases.

Avoid Premature Initialization

The only difference between the two cases is that, in the first example, the variable s is unnecessarily initialized. This is a separate issue from the location of the variable declaration. This adds two wasted instructions (to load a string constant and store it in a stack frame slot). A good static analysis tool will warn you that you are never reading the value you assign to s, and a good JIT compiler will probably elide it at runtime.

You could fix this simply by using an empty declaration (i.e., String s;), but this is considered bad practice and has another side-effect discussed below.

Often a bogus value like null is assigned to a variable simply to hush a compiler error that a variable is read without being initialized. This error can be taken as a hint that the variable scope is too large, and that it is being declared before it is needed to receive a valid value. Empty declarations force you to consider every code path; don't ignore this valuable warning by assigning a bogus value.

Conserve Stack Slots

As mentioned, while the JVM instructions are the same in both cases, there is a subtle side-effect that makes it best, at a JVM level, to use the most limited scope possible. This is visible in the "local variable table" for the method. Consider what happens if you have multiple loops, with the variables declared in unnecessarily large scope:

void x(String[] strings, Integer[] integers) {
  String s;
  for (int i = 0; i < strings.length; ++i) {
    s = strings[0];
    ...
  }
  Integer n;
  for (int i = 0; i < integers.length; ++i) {
    n = integers[i];
    ...
  }
}

The variables s and n could be declared inside their respective loops, but since they are not, the compiler uses two "slots" in the stack frame. If they were declared inside the loop, the compiler can reuse the same slot, making the stack frame smaller.

What Really Matters

However, most of these issues are immaterial. A good JIT compiler will see that it is not possible to read the initial value you are wastefully assigning, and optimize the assignment away. Saving a slot here or there isn't going to make or break your application.

The important thing is to make your code readable and easy to maintain, and in that respect, using a limited scope is clearly better. The smaller scope a variable has, the easier it is to comprehend how it is used and what impact any changes to the code will have.


In theory, it's a waste of resources to declare the string inside the loop. In practice, however, both of the snippets you presented will compile down to the same code (declaration outside the loop).

So, if your compiler does any amount of optimization, there's no difference.


In general I would choose the second one, because the scope of the 's' variable is limited to the loop. Benefits:

  • This is better for the programmer because you don't have to worry about 's' being used again somewhere later in the function
  • This is better for the compiler because the scope of the variable is smaller, and so it can potentially do more analysis and optimisation
  • This is better for future readers because they won't wonder why the 's' variable is declared outside the loop if it's never used later

If you want to speed up for loops, I prefer declaring a max variable next to the counter so that no repeated lookups for the condidtion are needed:

instead of

for (int i = 0; i < array.length; i++) {
  Object next = array[i];
}

I prefer

for (int i = 0, max = array.lenth; i < max; i++) {
  Object next = array[i];
}

Any other things that should be considered have already been mentioned, so just my two cents (see ericksons post)

Greetz, GHad


To add on a bit to @Esteban Araya's answer, they will both require the creation of a new string each time through the loop (as the return value of the some Assignment expression). Those strings need to be garbage collected either way.