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 project 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.)