Javascript how to create an allocation free animation loop to avoid garbage collector?

Viewed 1170

I'm trying to build a smooth 60fps animation browser javascript loop. I've noticed that the garbage collector kicks in and adds variable non-zero time to animation frames. I started by tracking down allocations in my code and then isolated the loop its self. I was using requestAnimationFrame and discovered that on a supposedly 'empty' loop It still causes allocations each iteration and triggers the garbage collector. Frustratingly this seems to happen in other looping mechanisms setInterval and setTimeout as well.

Below I've put together some jsfiddles and screenshots demonstrating the sample 'empty loops'. All the samples are from ~5 second timelines.

At this point, I'm looking for the best solution to minimize garbage collection. From the samples below it looks like requestAnimationFrame is the worst option in this regard.

requestAnimationFrame

https://jsfiddle.net/kevzettler/e8stfjx9/

var frame = function(){
    window.requestAnimationFrame(frame);
};

window.requestAnimationFrame(frame);

enter image description here

setInterval

https://jsfiddle.net/kevzettler/p5LbL1am/

var frame = function(){
   //literally nothing
};

window.setInterval(frame, 0);

enter image description here

setTimeout

https://jsfiddle.net/kevzettler/9gcs6gqp/

var frame = function(){
    window.setTimeout(frame, 0);
}

window.setTimeout(frame, 0);

enter image description here

2 Answers
Related