0

I'm using float buffers as direct byte buffers as required for opengl drawing in Android. The problem that is that upon creating the byte buffer, the GC goes crazy---as in 30s+ crazy. I'm creating a mesh of 40x40 vertices, or 1600 vertices, or 4800 floats. As per the profiler, the culprit that calls the GC is ByteBuffer.allocateDirect.

Is this normal or expected for creating a mesh this size? It seems pretty tame.

The buffer init() code is below:

public static FloatBuffer createFloatBuffer(int capacity) {
ByteBuffer vbb = ByteBuffer.allocateDirect(capacity * 4);
vbb.order(ByteOrder.nativeOrder());
return vbb.asFloatBuffer();
}
U Avalos
  • 6,538
  • 7
  • 48
  • 81

1 Answers1

1

Your question says allocateDirect, but your code says allocate. Which are you using?

allocateDirect is known to call System.gc in an attempt to force DirectByteBuffer to be reclaimed before trying (and failing) to allocate a new direct byte buffer.

See this answer for one suggestion on avoiding the GC. Alternatively, you could try creating a pool of appropriately-sized DirectByteBuffer rather than continuously creating new ones.

Community
  • 1
  • 1
Brett Kail
  • 33,593
  • 2
  • 85
  • 90
  • I had been playing with the code and forgot to change it back. The question still stands. The trace logs were done with allocateDirect() not allocate() – U Avalos Nov 02 '11 at 17:39
  • Took a look at the other stack questions. Unfortunately, that doesn't seem to apply in android. I don't see a DirectBuffer interface. So basically, what you are saying is create a bunch of smaller direct byte buffers instead of one large one? – U Avalos Nov 02 '11 at 17:46
  • No, I'm saying that after you create a byte buffer, you should hold on to the ByteBuffer object until the next time you need it. Don't repeatedly call allocateDirect. http://en.wikipedia.org/wiki/Object_pool_pattern – Brett Kail Nov 02 '11 at 21:48
  • oh I'm already doing that. I pretty much create only 3 byte buffers in total. Although each is pretty big---#1 represents 40x40x3 floats, #2 represents 40x40 shorts, #3 represents 40x40x2 floats. Still the first one to be initialized (#1) always causes the GC call, even when the others aren't created. So no other way to avoid that GC call? – U Avalos Nov 03 '11 at 18:09
  • Ah, then no, I don't have any other suggestions, sorry. – Brett Kail Nov 04 '11 at 15:48