Philip J Fry
Philip J Fry

Reputation: 53

Difference between defining variables inside and outside loops

In terms of style or performance, is it better to define variables within loops or outside of them?

For example:

int var;
for (...) {
    var = /*something*/;
    // Code that uses var
}

or

for (...) {
    int var = /*something*/;
    // Code that uses var
}

If you have any insight on how variable declarations work internally, and how one of these might perform better than the other (even if it's only slightly), please share. And outside of performance, which style is preferred?

Upvotes: 3

Views: 589

Answers (5)

Dan Grahn
Dan Grahn

Reputation: 9424

Inside

for(int i = 0; i < array.length; i++) {
   final String variable = array[i];
}
  • Keeps scope of variables limited.
  • Variable can be final
  • More readable (maybe)

Outside

String variable;
for(int i = 0; i < array.length; i++) {
   variable = array[i];
}
  • Variable is accessible outside loop.

For Each

for(final String variable : array) {
}
  • Only allocates once (source needed)
  • Keeps scope of variable limited.
  • Looks frickin' awesome.

Performance

The following test was run. It takes approximately 30s to run. The results show that there is no difference in performance between defining the variable inside or outside of the loop. This is most likely due to compiler optimizations. YMMV.

final double MAX = 1e7;

long start = System.nanoTime();
String var1;
for(double i = 0; i < MAX; i++) {
   var1 = UUID.randomUUID().toString();
}
System.out.println((System.nanoTime() - start) / 1e9);

start = System.nanoTime();
for(double i = 0; i < MAX; i++) {
   final String var2 = UUID.randomUUID().toString();
}
System.out.println((System.nanoTime() - start) / 1e9);

Discussion of Style Preference: https://stackoverflow.com/a/8803806/1669208

Upvotes: 5

moveaway00
moveaway00

Reputation: 917

The only time you should try to move the variable outside the loop, even if it's never used outside the loop is if you can re-use an object, and avoid using new on every iteration of the loop.

StringBuilder builder = new StringBuilder();
for(...) {
    builder.append(..);
    builder.append(..);

    strings[i] = builder.toString();
    // reset builder, to be used again
    builder.setLength(0);
}

This is much more efficient than making a new StringBuilder every time.

In all other cases, you should prefer to declare variables inside the loop if you can

Upvotes: 0

Anirudh
Anirudh

Reputation: 2326

Well, depends on how the variable is intended to be used primarily, if you are defining a variable inside a loop you would need to initialize the variable before the first use of the variable and in every run of the loop the variable would be re-initialized to this value.

On the other hand if you want to value of the variable to persist among different runs in the loop then you have to declare it outside. I don't think performance and style could be the primary criteria here.

Upvotes: 1

Kaushik
Kaushik

Reputation: 37

You should define for loop initialization variables in for loop header only which limits its scope within the loop. If you are concerned about performance then you should define variables within the loop.

Define variable outside loop only if you are using value of that variable outside loop as well.

Upvotes: 1

techPackets
techPackets

Reputation: 4516

If you declare the variable inside the for loop you won't be able to access it outside the loop.

for (...) {
    int var = /*something*/;
    // Code that uses var
}

you cannot access var outside the loop.

int var;
for(...) {
    var = /*something*/;
    // Code that uses var
}

var can be accessed outside the loop. Any other class code can use the value of var being set in the for loop.

Bottom line it all depends on your requirements.

Upvotes: 0

Related Questions