title: Speed up garbage collection in lapply
body: <p>What's the fastest way to do garbage collection in a <code>lapply</code> function or loop? What seems obvious to me slows things down enormously. Am I doing it wrong? Is there a quicker way?</p>
  
  <pre><code>x &lt;- 1:10000
  system.time(xx &lt;- lapply(1:length(x), function(xi) sum(x[1:xi])))
   user  system elapsed 
     0.02    0.00    0.02 
  system.time(xx &lt;- lapply(1:length(x), function(xi) sum(x[1:xi], invisible(gc(v=FALSE)))))
     user  system elapsed 
    22.49    0.00   22.57 # a thousand times increase in time taken!!
  </code></pre>
  
  <p>In my actual use-case the function is a bit more complex and fails without <code>gc</code> after every instance. I could switch to a machine with more RAM, though it would be less convenient, so I'm curious if there a faster <code>gc</code> method is available. </p>
  
  <p><strong>UPDATE</strong> Following Martin Morgan's suggestion, rearranging things slightly brings the speed up to close to the <code>lapply</code> without the <code>gc</code> (now working on a different machine, which is why timings are different from above):</p>
  
  <pre><code>x &lt;- 1:10000
  system.time(x1 &lt;- lapply(1:length(x), function(xi) sum(x[1:xi])))
     user  system elapsed 
     3.47    0.00    3.56 
  # define a function to make a sequence of a function followed by gc
  sum_gc &lt;- function(x) sum(x); invisible(gc(v=FALSE))
  system.time(x3 &lt;- lapply(1:length(x), function(xi) sum_gc(x[1:xi])))
     user  system elapsed 
     3.52    0.02    3.56 
  </code></pre>