Optimize bytecode for combination enhanced-for and enums

Dan Smith daniel.smith at oracle.com
Wed Mar 28 12:54:45 PDT 2012

On Mar 28, 2012, at 7:37 AM, Maurizio Cimadamore wrote:

> Another way to do this would be to generate a method that returns an Iterable<Edge> - and have the compiler rewrite
> for (Edge e : Edge.values()) { ... }
> into:
> for (Edge : edge$Values()) { ... }
> Here, the iterator creation is somewhat lighter than the array creation and the laziness of this scheme makes sure that nothing gets initialized if the method is not called at all.

Might as well generate that method in the enum class itself (and specify it appropriately -- JLS 8.9.2):

class Edge extends Enum<Edge> {
  static E[] values() { ... }
  static Iterable<E> valuesIterable() { ... }
  static E valueOf(String s) { ... }

Then the only use-site optimization is for the compiler to turn Edge.values into Edge.valuesIterable, knowing that both will have the same effect in this code.

It would be nice if there were a better name, so that users would be inclined to just refer to "valuesIterable" directly...  For loops are not the only place that a writeable array is not needed, but we can't hope to catch them all with fancy optimization tricks.


More information about the compiler-dev mailing list