Hi community!
When I was young and used to code in C++, I loved the possibility to allocate objects locally on the stack. E.g.
CMatrix temp( getPosition() );
In Java, the direct counterpart would be
Matrix4f temp = new Matrix4f( getPosition() );
Well, there is the bad word ‘new’ in it. I’m afraid to create garbage by that. An alternativ is to hold a and reuse a preallocated instance:
private final Matrix4f mTemp = new Matrix4f();
...
mTemp.set( getPosition() );
But this is ugly, not threadsafe and consumes memory that is only temporarily used.
Now, how big is the overhead of that special kind of ‘new’ for temporary objects? Can the compiler or the JVM determine that it’s local, allocate it on the stack and remove it quickly when the scope is left?
I read some things about HotSpot dealing with different kinds of objects concerning their lifetimes, but I’m not ready to understand it and apply it to this case. Anybody to help me out?