Java – the difference between defining variables inside and outside a loop

In terms of style or performance, is it better to define variables inside or outside the loop?

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 into how variable declarations work internally, and how one declaration is better than the other (even if it's only slightly), please share Besides performance, which style is more popular?

Solution

within

for(int i = 0; i < array.length; i++) {
   final String variable = array[i];
}

>Keep variable range limited. > Variables can be final > more readable (possible)

Outside

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

>Variables can be accessed outside the loop

everybody

for(final String variable : array) {
}

>Assign only once (source required) > keep variable range limited. > It looks great

performance

Perform the following tests It takes about 30 seconds to run The results show that there is no difference in performance between variables defined inside or outside the loop This is probably due to compiler optimization differ from man to man.

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 preferences: https://stackoverflow.com/a/8803806/1669208

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>