[quote=“Roquen,post:16,topic:55568”]
I encountered this problem in LWJGL recently and it’s still exactly like what you describe. The usual failure case looks like:
- User code allocates an object and passes it to a method
- which calls a simple method
- which calls a simple method
- …
- which calls a complex method that uses the allocated object
Assuming that all these methods are pure and do not leak the reference anywhere else, the allocation will still occur if the final method is too big to be inlined. If the final method is in library code, one thing you could do without affecting user-code is:
// before
public static void complexMethod(..., MyClass object) {
// lots of bytecode...
}
// after
public static void complexMethod(..., MyClass object) {
complexMethodImpl(..., object.fieldA, object.fieldB, ...);
}
private static void complexMethodImpl(..., MyClassFieldA fieldA, MyClassFieldB fieldB, ...) {
// lots of bytecode...
}
This lets complexMethod get inlined and escape analysis will eliminate the MyClass object allocation.
As an example, the case I’m currently optimizing in LWJGL is [icode]GL20.glShaderSource(int shader, CharSequence… strings)[/icode] and “complexMethod” is UTF-8 encoding the input strings. With the above trick, allocation of the intermediate ByteBuffers is eliminated.
(not that you’d ever call glShaderSource so many times that it’d be a problem, but the same solution can be applied to similar scenarios)