Field access optimisations inside loops (question).
dawid.weiss at gmail.com
Fri Jan 8 07:11:00 PST 2010
Thanks for the discussion, Ulf, I appreciate your time. I still think
the compiler COULD optimize here -- I attach a simple JUnit test case
that shows the self-contained example (clearly there is no way
anything can be modified with the list of buffer fields and the first
loop is still much, much slower).
> BTW 1: your example 2 is common practice to increase java code. For short,
> you could use:
I couldn't really do this because these classes are template-generated
and the buffer type is not always matching
the counter's type. Anyway, this does not bloat the bytecode that much
and at runtime there is no difference between local scope declarations
and inline declarations (I believe due to variable scope analysis
> BTW 2: Good trick, to prevent from dead code elimination by public static
> volatile target.
Not mine (saw it somewhere, one day) but thanks.
P.S. Self contained example, if you care to look.
public class IntArrayListBenchmark
private static class IntArrayList
private final int size;
private final int  buffer;
public IntArrayList(int size)
this.buffer = new int [size];
this.size = size;
public int size()
public int get(int i)
// modify to your liking...
public static int CELLS = (1024 * 1024) * 10;
private final IntArrayList list = new IntArrayList(CELLS);
public static volatile int value;
public void testSimpleGetLoop() throws Exception
for (int i = 0; i < list.size(); i++)
value = list.get(i);
public void testDirectBufferLoop() throws Exception
final int size = list.size();
final int  buffer = list.buffer;
for (int i = 0; i < size; i++)
value = buffer[i];
public void testCompactBufferLoop() throws Exception
for (int i = 0, size = list.size(), buffer = list.buffer;
i < size; i++)
value = buffer[i];
More information about the hotspot-compiler-dev