I am new to Java and I am building small school project for android. If I have a nested for loop:
for (int i = 0; i <1000; ++i) {
for (int j = 0; j <1000; ++j) {
// .. this code will be executed a 1,000,000 times
}
}
Does it affect performance that j is declared on each iteration of the outside loop? If yes, what's a good way to fix it? It is school projec开发者_StackOverflowt so I have to write code that uses smallest amount of memory. Thank you!
No, it doesn't, and it's good practice to declare the variable in as limited a scope as possible - it makes it clearer for readability. It also ensures that you're not accidentally using the value from the end of one loop at the start of the next.
(Personally I'd be wary of anyone forcing you to use the absolute minimum amount of memory instead of concentrating on readability and measured optimization where it matters.)
Declaring nested variables has no affect on performance, in fact it is recommended so that the variable's use is restricted to the correct scope. This just helps avoid simple mistakes.
The only way to now is to try it different ways. I can tell you that it is more than likely not going to be a performance problem, and generally you don't worry about optimizing until it is a known problem.
No it does not affect performance.
The way you wrote it is the best way: always declare a variable so that its scope is no larger than necessary.
And let the compiler optimize performance.
There is a performance impact for allocating the integer. However, it is so ridiculously small that I wouldn't bother doing it different. A well-known saying goes "premature optimization is the root of all evil".
EDIT: tested it with System.nanoTime()
after Jon's comment. Not one bit of difference whether you "pre-declare" it or not. So I was wrong about there being any impact.
精彩评论