3

In brief, this is what I do :

public void method(List<Integer> elems) {
    final int MAX_ELEM_COUNT = 32;
    ByteBuffer bb == ByteBuffer.allocate(MAX_ELEM_COUNT * Integer.BYTES);

    for (Integer elem : elems) {
         bb.putInt(elem);
    }

    bb.flip();

    ByteBuffer dest = getPermanentBufferForSize(bb.remaining());
    dest.put(bb);
}

Temporary buffer is quite small(128 bytes) and it's not escaping so looks like a good fit for stack allocation. (ByteBuffer object itself & byte array it references).

Do JVM's (especially OpenJDK) ever do it for arrays?

If they do, what are the requirements to trigger this kind of escape analysis? (I'm looking for implementation details of JVM's, things like : It must be smaller than 4 kb, allocation size must be known on compilation time, it's reference must not be assigned to a heap object etc..) Any resource is appreciated.

vkx
  • 424
  • 1
  • 7
  • 17
  • Possible duplicate of [Escape analysis in Java](https://stackoverflow.com/questions/771430/escape-analysis-in-java) – luketorjussen Aug 04 '18 at 20:43
  • 2
    The Java Magazine a few months ago had an article about Escape analysis http://www.javamagazine.mozaicreader.com/MarApr2018/Default/73/0/3947345#&pageSet=73&page=0, and then another about lock elision (which also looked into EA and with arrays) - http://www.javamagazine.mozaicreader.com/MayJune2018/Default/74/0/3978350#&pageSet=82&page=0 you may need to subscribe to read them, but it is free to do so. – luketorjussen Aug 04 '18 at 20:48
  • @luketorjussen I'm quite surprised that default EA limit is 64 for arrays. I never tested with less than 128 so I didn't see any performance difference. Now I get stack allocated array for 64+ arrays with XX:EliminateAllocationArraySizeLimit. If you post it as an answer, I can accept it. Thank you. – vkx Aug 04 '18 at 22:20
  • glad this helped. I've added it as an answer – luketorjussen Aug 05 '18 at 18:39

1 Answers1

3

This was discussed in an article in the Java Magazine

The default size limit for arrays to be escaped (at the time of writing) is 64, but it can be tuned via the -XX:EliminateAllocationArraySizeLimit=N flag.

luketorjussen
  • 3,156
  • 1
  • 21
  • 38