Search code examples
garbage-collectionreal-timedframe-rate

Could calling core.memory's GC.collect consistently make for a more consistent framerate?


I'm looking into making a real time game with OpenGL and D, and I'm worried about the garbage collector. From what I'm hearing, this is a possibility:

  • 10 frames run
  • Garbage collector runs kicks in automatically and runs for 10ms
  • 10 frames run
  • Garbage collector runs kicks in automatically and runs for 10ms
  • 10 frames run
  • and so on

This could be bad because it causes stuttering. However, if I force the the garbage collector to run consistently, like with GC.collect, will it make my game smoother? Like so:

  • 1 frame runs
  • Garbage collector runs for 1-2ms
  • 1 frame runs
  • Garbage collector runs for 1-2ms
  • 1 frame runs
  • and so on

Would this approach actually work and make my framerate more consistent? I'd like to use D but if I can't make my framerate consistent then I'll have to use C++11 instead.

I realize that it might not be as efficient, but the important thing is that it will be smoother, at a more consistent framerate. I'd rather have a smoothe 30 fps than a stuttering 35 fps, if you know what I mean.


Solution

  • Yes, but it will likely not make a dramatic difference.

    The bulk of time spent in a GC cycle is the "mark" stage, where the GC visits every allocated memory block (which is known to contain pointers) transitively, from the root areas (static data, TLS, stack and registers).

    There are several approaches to optimize an application's memory so that D's GC makes a smaller impact on performance:

    • Use bulk allocation (allocate objects in bulk as arrays)
    • Use custom allocators (std.allocator is on its way, but you could use your own or third party solutions)
    • Use manual memory management, like in C++ (you can use RefCounted as you would use shared_ptr)
    • Avoiding memory allocation entirely during gameplay, and preallocating everything beforehand instead
    • Disabling the GC, and running collections manually when it is more convenient

    Generally, I would not recommending being concerned about the GC before writing any code. D provides the tools to avoid the bulk of GC allocations. If you keep the managed heap small, GC cycles will likely not take long enough to interfere with your application's responsiveness.