title: Why do my svg nodes leak memory in IE
body: <p><em>Background: Inspired by <a href="https://stackoverflow.com/questions/18364956/are-event-listeners-for-removed-automatically-when-using-remove-in-d3-js">this question</a> and <a href="https://stackoverflow.com/questions/18382286/d3-js-should-i-detach-event-listener-on-exit-remove">this question</a> about D3 memory usage I decided to dig into how it really works, and soon came upon <a href="http://com.hemiola.com/2009/11/23/memory-leaks-in-ie8/" rel="nofollow noreferrer">cautions about repeated add/remove of DOM nodes in IE</a>.</em></p>
  
  <p>To isolate from whatever else D3 was doing, I first tried the basic SVG case of adding/removing 1000 circles every second:</p>
  
  <pre class="lang-js prettyprint-override"><code>var count = 1000;
  var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  svg.setAttribute('width', '800');
  svg.setAttribute('height', '800');
  document.body.appendChild(svg);
  
  function update() {
    // remove existing circles
    var circles = svg.querySelectorAll("circle")
    for (var i = circles.length - 1; i &gt;= 0; i--) {
      var parent = circles[i].parentNode;
      if (parent) parent.removeChild(circles[i]);
    };
  
    // add new ones. Yes, would make more sense to update the x,y on the existing
    // circles but this is to show what happens in IE with lots of nodes being added/removed
    for (var j = count - 1; j &gt;= 0; j--) {
      var node = document.createElementNS("http://www.w3.org/2000/svg", 'circle');
      node.id = 'id' + Math.random();
      node.setAttributeNS(null, "cx", Math.random()*800);
      node.setAttributeNS(null, "cy", Math.random()*800);
      node.setAttributeNS(null, "r",  5);
      node.setAttributeNS(null, "fill", "blue");
      svg.appendChild(node);
    };
  }
  
  setInterval(update, 1000);
  </code></pre>
  
  <p>I found that this slowly leaks memory in both IE9 and IE10. See here for live version: <a href="http://bl.ocks.org/explunit/6413259" rel="nofollow noreferrer">http://bl.ocks.org/explunit/6413259</a></p>
  
  <p><strong>What (if anything) can I do to prevent the leak, and what implications does this have for how D3 code targeting IE should be written that adds/removes a lot of nodes?</strong></p>
  
  <p>Other notes: </p>
  
  <p>Inspired by <a href="http://www.html5rocks.com/en/tutorials/speed/static-mem-pools/" rel="nofollow noreferrer">this article</a>, I tried a simple node pool approach by pushing the removed nodes on to a stack:</p>
  
  <pre><code>if (parent) circlePool.push( parent.removeChild(circles[i]) );
  </code></pre>
  
  <p>And reusing them later:</p>
  
  <pre><code>var node;
  if (circlePool.length == 0) {
    node = document.createElementNS("http://www.w3.org/2000/svg", 'circle');
  } else {
    node = circlePool.pop();
    //TODO: clear out attributes of the node
  }
  </code></pre>
  
  <p>But this did not make any difference.</p>