An enterprise question on local field definition in a loop
Hi all,
I have two situation as follows, one is to define A a in a loop, the other is to define A a outside loop. From enterprise view, which is better, ot both are same. Thank you so much in advance.
--
List<A> aList = new ArrayList<A>();
for (int i = 0; i < 10; i++) {
A a = new A();
aList.add(a);
}
--
List<A> aList = new ArrayList<A>();
A a = null;
for (int i = 0; i < 10; i++) {
a = new A();
aList.add(a);
}
[537 byte] By [
sheng.gua] at [2007-11-27 5:15:05]

They're pretty much the same since the compiler and the JVM will optimize it after all and allocate the stack for all variables already before entering the method. I'd expect to get exactly the same bytecode. (Haven't tried though.)
Stylewise, I prefer the first way because it minimzes the variable's scope.
And what is an "enterprise view"? Both of them generate about the same revenue...
Hi CeciNEstPasUnProgrammeur ,Thank you very much for your reply. What I think about "enterprise view" is that in an enterprise project, both the two situations have the same memory consumption and garbage collection? Thanks.
> Thank you very much for your reply. What I think
> about "enterprise view" is that in an enterprise
> project,
It's just Java... it doesn't behave differently in different project scales.
> both the two situations have the same memory
> consumption and garbage collection?
Yes. How would the memory consumption differ anyway? 4 kB of reference created and released vs. 4 kB of reference created, released, created, released... (Though I said before, the latter does not happen anyway.)
GC might not be able to clean up the last object in the second way if it happens to run just after the loop exited because you still have a valid reference to it, but that's purely academic.