As for performance, I don't know, I usually don't work on systems where this level of performance optimization would be meaningful (not in years anyway). I would think that with compilers being as smart as they are now, the performance would be about the same as they are allowed to re-arrange declarations and assignments to optimize speed. But perhaps someone else has better experience than I do.
Balagopal Kannampallil wrote:In the second loop the newly created objects inside the loop will take more time to get Garbage collected as the number of references are more when compared to the first loop.
Well we are adding those Objects in arrayList so I dont think that GC will come into picture because in both of these loops arrayList visibility is same.
Here is the quote from EFH that I have copied from my old post
EFH wrote:a reference is just a reserved spot on the stack, and absolutely nothing is done at runtime to "create" one. Therefore this loop has an empty body; the Hotspot compiler is likely to optimize it away completely.
A reference has any importance when an object is associated to it. So in your case scope is the only thing that differs in given two loops. And it's already been pointed out by other people.
This should surely clear the confusion.
Himanshu Gupta wrote:Thanks everyone for your replies. In my code review i coded using the Loop2 style.... and it came back as a defect....
It might be considered a defect in C++, but in Java, it honestly makes no difference at all. The compiler will generate the exact same bytecode, in fact, with one small difference: in version 1, obj, arr, and i will be in registers 1, 2, and 3, respectively, while in version 2 they'll be in 3, 1, and 2 -- just because the order in which they're first mentioned changes.
It might be considered a defect in C++, but in Java, ....... order in which they're first mentioned changes.
Thanks for your reply Ernest.
I got something which states that Loop1 style is more efficient as compared to Loop2. But the reason is not given there and I am also not able to find out. src
I think in any meaningful application, these micro-optimizations are far less important than the efficiency of database access, remote method calls, webservice calls etc
Himanshu Gupta wrote:You are right Marky but the question is what makes Loop1 more efficient?
Nothing does - it's not more efficient. The author of JAC_052 is, how can I put this gently? Full of crap. Ignore it.