What is optimal?

Declares a variable inside the loop good or declares "on the fly" optimal in Java. Also, is there any cost to performance when declaring inside a loop?

eg.

Option 1: Out of Circuit

List list = new ArrayList(); int value; //populate list for(int i = 0 ; i < list.size(); i++) { value = list.get(i); System.out.println("value is "+ value); } 

Option 2: inside the loop

 List list = new ArrayList(); //populate list for(int i = 0; i < list.size(); i++) { int value = list.get(i); System.out.println("value is "+ value); } 
+4
source share
8 answers

In Clean Code, Robert C. Martin advises Java code machines to declare variables as close as possible to where they should be used. Variables should not have more volume than necessary. Having a variable declaration close to where it is used provides information about the type of reader and initialization. Don't worry too much about performance, because the JVM optimizes these things pretty well. Instead, focus on readability.

BTW: if you use Java 5 or more, you can significantly reduce your sample code using the following new-for-Java-5 functions:

  • foreach construction
  • generics
  • Autoboxing

I updated your example to use the above new features.

 List<Integer> list = new ArrayList<Integer>(); // populate list for (int value : list) { System.out.println("value is " + value); } 
+12
source

You should not understand which method you are implementing in terms of performance.

But more importantly, you should not waste time micro-optimizing your code like this ... IF you have profiled your entire application and decided that this snippet is a performance bottleneck. (And if you did, you have a good opportunity to see if there is any difference between the two versions of the code. But I would be very surprised if I were ...)

+1
source

While your example is a hypothetical, most likely not a real world application, the simple answer is that you don't need a variable at all in this scenario. There is no reason to allocate memory. Simply put, this is a lost memory that becomes cannon fodder in the JVM. You have already allocated memory to store the value in the list, why duplicate it in another variable?

The scope of a variable will often determine where it should be declared. For instance:

 Connection conn = null; try { conn.open(); } catch (Exception e) { e.printStackTrace(); } finally { conn.close(); } 

Other answers are good at exposing other pitfalls of the example you provided. There are more efficient ways to iterate through the list, regardless of whether it will be with the actual Iterator, or foreach loop, and generics, this will help eliminate the need for a primitive duplicate.

+1
source

Well, if you're worried about optimizing this code - I'm not sure how Java evaluates loops, but having list.size() called inside a loop declaration may be less efficient than exiting a loop (and setting it to maybe maybe varable listLength ). I'm sure JavaScript is faster in JavaScript. The reason this might be more efficient is because when calling the size function inside the for loop, it will have to call the function every time it runs a test to check if the loop is complete, instead of checking for a static value.

0
source

The best way to go through the list is to use Iterator.

 for (Iterator iter=list.iterator(); iter.hasNext();) { System.out.println(iter.next()); } 
0
source

In simple cases like this, there is most likely no difference, and the compiler produces the exact same code (provided that you do not set the initial value when declaring a variable).

In more complex cases and longer functions, declaring a local variable inside a loop or other block is likely to be more efficient. This reduces the lifetime of the variable, which makes it easier for the compiler to optimize the code. When a variable does not exist outside the block, the register used to store the variable can be used for other purposes.

This, of course, depends on the compiler implementation. I do not know about Java, but at least some manufacturers of C compilers have given this recommendation in their documentation.

Regarding readability, I believe that in short functions it is better to declare all variables at the beginning, where they can be easily found. In very long functions (which should be avoided anyway), it might be better to declare a variable inside the block (which may also be more efficient).

0
source

In addition to the useful suggestions given by others, please remember one thing:

will never be optimized early. If you really think your code is slow and may need to be improved, then use the profiler for your code to determine where the bottlenecks are, and only then reorganize them. Find out where the error was. Do not repeat the error the next time.

In your case, I would say that depending on the version of Java Java, your performance (guess what) may change. From experience, I did not declare a variable in the loop; int will, of course, be optimized by the compiler and reuse the same memory address, and additional computational overhead can be negligible.

But.

If you declare an object inside a loop, everything will be different. What if your object, when it is created, writes I / O? Network DNS lookup? Perhaps you do not know / do not care. Therefore, the best practice is to declare it ouside.

Also, do not mix performance with best practices. They can lead you to dangerous territory.

0
source

The Java compiler determines the number of “slots” that it needs in the stack frame, depending on how you use local variables. This number is determined based on the maximum number of active locales at any given point in the method.

If your code is only

 int value; for (...) {...} 

or

 for (...) { int value; ... } 

the runtime stack requires only one slot; the same slot can be reused inside the loop no matter how many times the loop runs.

However, if you do something after a loop requiring a different slot:

 int value; for (...) {...} int anotherValue; 

or

 for (...) { int value; ... } int anotherValue; 

we will see the difference - the first version requires two slots, since both variables are active after the cycle; in the second example, only one slot is required, since we can reuse the slot from "value" for "anotherValue" after the loop.

Note: the compiler may be smarter with respect to optimization depending on how the data is actually used, but this simple example is intended to demonstrate that there may be a difference in the distribution of the stack frames.

0
source

All Articles