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.
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.