LWJGL Forum

Programming => Lightweight Java Gaming Library => Topic started by: hapsky on May 10, 2012, 15:58:33

Title: BufferUtils.createFloatBuffer and memory problems
Post by: hapsky on May 10, 2012, 15:58:33
Hello,

I ran into this problem: suppose I have a method that gets called a few times every frame at about 100fps. Inside this method I create a new Vector3 object. The Vector3 class is my own personal implementation, and contains a private FloatBuffer.


public class Vector3
{
    ...
    private FloatBuffer mBuffer = BufferUtils.createFloatBuffer( 3 );
    ...
}


I use that float buffer to store the x y and z coordinates and to quickly return them if I need to use the vector with the opengl api.

The problem is, the garbage collector is having a hard time cleaning up my Vector3 objects, so with only that initial method creating one Vector3 object, my memory consumption skyrockets to about 500mb ( it normally only uses 40mb ). Reading about ByteBuffers on the javadoc page, I see they are treated specially from the memory point of view. They also recommend "It is therefore recommended that direct buffers be allocated primarily for large, long-lived buffers".

Is there a nice way to convert from vectors ( and matrices ) to FloatBuffers ?

Thanks.
Title: Re: BufferUtils.createFloatBuffer and memory problems
Post by: Fool Running on May 11, 2012, 12:48:54
I think most people (me included) have their Vector3 class just store 3 floats. When you need to pass it to OpenGL you then use a FloatBuffer that you have waiting; one that is created to a certain size (mine is 16 floats) that you can just stick random stuff in it any time you need. You don't ever throw away the FloatBuffer and just keep using it for whatever you need it for (making sure to flip() after putting stuff in it ;)).
Title: Re: BufferUtils.createFloatBuffer and memory problems
Post by: hapsky on May 11, 2012, 18:09:43
That's a pretty good idea and I should have thought of it. Makes me feel silly. Thank you :)