Question about foreach-over-array desugaring.

Sergey Bylokhov Sergey.Bylokhov at oracle.com
Tue Mar 4 15:53:33 UTC 2014


Hello.
I became interested in a question of the foreach-over-array conversion 
to the old version of for.
According to specification foreach should be transformed to
JLS 14.14.2:
T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
     VariableModifiersopt TargetType Identifier = #a[#i];
     Statement
}

And javac generates exactly the same code. But we generate this 
assignment "T[] #a = Expression;" even in case of an Expression is a 
reference to the local array, is it correct?
This is obvious when a nested loops are used:
T[] #a = Expression;
........
for (int #i = 0; #i < #a.length; #i++) {
     VariableModifiersopt TargetType Identifier = #a[#i];   // first 
assignment
     T[] #a1 = Identifier;  //second assignment
     ...........
for (int #i1 = 0; #i1 < #a1.length; #i1++) {
         VariableModifiersopt TargetType Identifier = #a1[#i1];
     ............
}
}

This behavior is by design, or nobody paid any attention to it? Sure, I 
know that javac usually left all optimizations to the runtime, but it is 
simply curious and interesting.

-- 
Best regards, Sergey.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.openjdk.java.net/pipermail/compiler-dev/attachments/20140304/fbb0c758/attachment.html 


More information about the compiler-dev mailing list