Hello there,

I've been looking for this kind of information for some time, but still haven't been able to find it. I've heard from some people that it's actually faster if you declare a variable outside a loop than inside, even if you assign it a new value each iteration. For example:

Point p;
for (int i = 0; i < 10; i++) {
p = new Point(i, i);
}

is said to be faster than:

for (int i = 0; i < 10; i++) {
Point p = new Point(i, i);
}

However, the second option is much more elegant, less error-prone (since the variable is inside the loop) and it doesn't seem hard for the compiler to see such a thing and optimize for it.

If the first code actually runs faster than the latter, then it would be useful to be able to do something like:

for (int i = 0, Point p = null; i < 10; i++) {
p = new Point(i, i);
}

I'd like also to know about other variations, such as:

for (int i = 0; i < 10; i++) {
double d = (double)i;
}

versus:

double d;
for (int i = 0; i < 10; i++) {
d = (double)i;
}

or even:

for (int i = 0, double d = 0; i < 10; i++) {
d = (double)i;
}


And, also, if the final modifier could make things faster:

for (int i = 0; i < 10; i++) {
final Point p = new Point(i, i);
}


Thanks in advance,
Dhakir.