I’m trying to find a may to minimize memory allocation and garbage collection in a Java OpenGL (JOGL) application. I am porting some C/C++/C# OpenGL project to Java as a learning exercise. One thing I am running into is the lack of pointers in Java and the allocation of objects and GC of them as the application runs. In C/C++/C# I can get the applications to startup and simply run without allocating any additional memory or objects by passing references around but in Java it seems my designs are incompatible.
As these designs have evolved they are using higher level objects. In C they were structs for Vectors and Matrices and in C++/C# classes. These all essentially boil down to arrays of bytes in memory. Which are then cast in one way or another to float[] for OpenGL calls or object arrays internally within the application so I can us object based operations like operator overloading, add and multiply, or property accessing for example. Anyone working with OpenGL probably sees what I am doing. This way I allocate everything on load and simply pass the data around.
Java has thrown me for some loops. It appears I cannot cast data back and forth thus I keep creating lots of data and the GC comes by and does it work. This is noticeable by resources being consumed and cleaned up and a noticeable stutter during the application run. I have alleviated some of this by creating FloatBuffers in addition to VectorXf arrays for my geometry data and pass the FloatBuffer down to OpenGL. But when I need to update Vector data I have to recopy the data back to the float buffer. This also means I am storing double the data and incurring the overhead of the floatbuffer fills.
I’d like to hear how others are dealing with these issues. I’d like to keep the higher order objects for the functionality built in but be able to pass the data to OpenGL. Are my designs simply incompatible with Java? Do I need to move to FloatBuffers exclusively? How does one pass component data into a higher order object without the penalty of object creation. So many OpenGL applications exist that I suspect there is some ‘magic’ to utilize either the same buffer for float[] and Object[] or allocate contiguous block for object data and pass a reference to OpenGL.
My experience: I was using FloatBuffers for only transferring data, but I found that this was really performance killing for dynamic meshes because I had to transform my Vec arrays to FloatBuffers everytime I change my meshes. Now I got rid of my vec arrays and only use FloatBuffers persistently through my mesh classes, less elegant to handle them but much faster. So I would advise you to keep & update all your geometry data with FloatBuffers