title: Javascript memory usage in for loop
body: <p>I try to profile memory usage in nodejs (0.10.35), I created 2 files below and run with node --expose-gc </p>
  
  <p>var a and var b are initialized as empty string</p>
  
  <p>A for loop is run to make a and b bigger</p>
  
  <p>setInterval prints out the memory usage every 1 second</p>
  
  <p>The x >> 20 operator is equivalent to Math.floor(x/1024/1024) to give the result in MB</p>
  
  <pre class="lang-js prettyprint-override"><code>//file 1.js
  
  var a = '', b = '', n = 0;
  var i = 10000000; for (;i;i--) {a += i; b += i;}}
  
  setInterval(function(){
      var m = process.memoryUsage();
      console.log(++n,m.rss&gt;&gt;20,m.heapTotal&gt;&gt;20,m.heapUsed&gt;&gt;20);  
  },1000);
  
  setTimeout(function(){  
      global.gc();
      console.log('1st garbage collect');
  },2500);
  
  setTimeout(function(){
      a = null;
      console.log('var a cleared');   
  },5000);
  
  setTimeout(function(){
      global.gc();
      console.log('2nd garbage collect');
  },7500);
  
  //file 2.js is similar to file 1 except that var a and var b are changed at separate loops
  var i = 10000000; for (;i;i--) {a += i;}
  var i = 10000000; for (;i;i--) {b += i;}
  </code></pre>
  
  <p>I got the results from console</p>
  
  <pre class="lang-none prettyprint-override"><code>     1.js                  2.js
  1    1098 1073 1069        1407 1378 1375
  2    1098 1073 1069        1407 1378 1375
       1st garbage collect
  3    1098 1073 1069        715 696 688
  4    1098 1073 1069        715 696 688
       var a cleared
  5    1098 1073 1069        715 696 688
  6    1098 1073 1069        715 696 688
  7    1098 1073 1069        715 696 688
       2nd garbage collect
  8    19   11   1           20  12  1
  </code></pre>
  
  <p>My questions are:</p>
  
  <ol>
  <li>The a.length and b.length is only ~ 65 MB, why the memory usage ~1000 MB in file 1.js and ~1400 MB in file 2.js</li>
  <li>After the 1st garbage collection, wouldn't var b be collected but it looks like the memory usage is still > 1000 MB for file 1.js, but ~700 MB in file 2.js?</li>
  </ol>
  
  <p>After the 2nd garbage collection, the memory drops to &lt; 20 MB, as expected. Am I looking at something wrong here?</p>