Javascript how to create an allocation free animation loop to avoid garbage collector?
<p>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 <code>requestAnimationFrame</code> 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 <code>setInterval</code> and <code>setTimeout</code> as well.</p>

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

<p>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.</p>

<p><strong>requestAnimationFrame</strong></p>

<p><a href="https://jsfiddle.net/kevzettler/e8stfjx9/" rel="noreferrer">https://jsfiddle.net/kevzettler/e8stfjx9/</a></p>

<pre><code>var frame = function(){
    window.requestAnimationFrame(frame);
};

window.requestAnimationFrame(frame);
</code></pre>

<p><a href="https://i.stack.imgur.com/fAcal.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fAcal.png" alt="enter image description here"></a></p>

<p><strong>setInterval</strong></p>

<p><a href="https://jsfiddle.net/kevzettler/p5LbL1am/" rel="noreferrer">https://jsfiddle.net/kevzettler/p5LbL1am/</a></p>

<pre><code>var frame = function(){
   //literally nothing
};

window.setInterval(frame, 0);
</code></pre>

<p><a href="https://i.stack.imgur.com/brTj0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/brTj0.png" alt="enter image description here"></a></p>

<p><strong>setTimeout</strong></p>

<p><a href="https://jsfiddle.net/kevzettler/9gcs6gqp/" rel="noreferrer">https://jsfiddle.net/kevzettler/9gcs6gqp/</a></p>

<pre><code>var frame = function(){
    window.setTimeout(frame, 0);
}

window.setTimeout(frame, 0);
</code></pre>

<p><a href="https://i.stack.imgur.com/MUPjE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MUPjE.png" alt="enter image description here"></a></p>