First, are you sure the comparison is the same? Of course assigning a value outside the loop is supposed to be faster. Already declaring should be the same. But not necessarily.
It has to measure. And it needs to measure in several different situations. Even if it makes a difference, I think it will be small.
Note that there may be even different semantics in declaring outside or inside the loop. I don’t know how it is in Java. I can search. But I agree with the comment of mgibsonbr, there should be no difference in most situations.
The first creates a variable outside and then assigns new values in each step. In the second the variable is created again and the value is assigned.
Some people will think that creating the variable again will have a memory or processing cost, but it doesn’t have to happen. In general it will be allocated on my site from stack and no processing will be necessary. Then it is to be equal. But I do not guarantee that there are no exceptions in specific circumstances. I’d have to read the spec to see if there’s any catch.
I would choose what is the most semantically correct for the case, or if it makes no difference I think it would be stating inside the loop, unless I need performance and a thorough analysis demonstrate that stating outside is best.
A hint that is not related to the above case: quantitative experience is different from qualitative. I know programmers with 30 years of experience who do everything wrong and do not insist on improving. There are teachers who are jealous of what they are teaching and others do not. Often the teacher says one thing and the student understands another :)
Related: Good practices in declaring variables in a for has another question (which I didn’t find) about the cost of some interesting for(s) styles as well.
– rray
It depends on the compiler, I’m not sure but I believe that all modern compilers will generate the same code for one version or another. Try "decompile" these two examples using
javap
and see what happens. For more details, see the question suggested by @rray.– mgibsonbr
Related/found :P There is difference between reporting the size in the loop condition or outside of it?
– rray
@rray but this ñ has so much to do, has different semantics whenever the value to be compared can be modified at each step
– Maniero