1

When creating arrays in javascript and then removing all the pointers to that array, the garbage collector will eventually free the memory used by the array. The problem is that in a game where you want a stable framerate, the garbage collection could cause frame rate stuttering.

Graph showing how the garbage collection cause reduction in framerate To prevent these fps drops, I want to create the array in advance, but the problem is I don't know how large the array should be. I Assume, starting with a array of 0 length and then increasing it would cause memory to be assigned and freed, as the array fills up, but will reducing the length of the array using operations like pop() or setting the length of the array to 0 cause re-assignement of memory and give work to the garbage collector?

let someArray = [];
// ... Inside game loop...
someArray.push(newElement); // Here memory might be re-allocated if the array increases too much.
// ...
someArray.length = 0; // Could this cause the array to be re-allocated to a smaller chunk of memory? Could this trigger garbage collection?
Markus Fjellheim
  • 335
  • 2
  • 11
  • Yes, definetly. But usually GC doesn't kick in until the memory gets filled up too much ... – Jonas Wilms Feb 05 '19 at 19:03
  • things to avoid if you want to limit garbage collection: https://stackoverflow.com/questions/18364175/best-practices-for-reducing-garbage-collector-activity-in-javascript – IrkenInvader Feb 05 '19 at 19:04
  • I presume you're asking about V8 specifically? There are different GC implementations, and it's possible to implement a pause-free hard realtime GC (I recall reading a paper about that a couple of years ago but I don't have a reference offhand). – Daniel Pryden Feb 05 '19 at 19:17
  • @JonasWilms In my case the memory gets filled up pretty fast, a major GC kicks in about every 30 seconds, and minor stuttering in between. – Markus Fjellheim Feb 06 '19 at 12:17
  • @IrkenInvader Thanks, I'm implementing the techniques, and I see improvement in my game already! – Markus Fjellheim Feb 06 '19 at 12:18

0 Answers0