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.
source share