Last updated

RSpec speed-up (24.6%) by tweaking ruby garbage collection

[Today I learned][1] that Ruby garbage collection can be of huge importance to performance. More precisely, if Ruby does a lot of garbage collection it may slow down your code. Running garbage collection only every 10 or 20 seconds when running specs may increase performance dramatically.

At this time specs for Ariejan.net take an average of 25.29s to run. This is not bad, but in my opinion faster specs are better. After tweaking ruby garbage collection I got my specs to run in 19.05s, a 24.6% speed increase! [1]: http://37signals.com/svn/posts/2742-the-road-to-faster-tests ~ So, how do you speed up your tests?

The key is that you don’t want ruby to decide when to do garbage collection for you. Instead, we’ll tell Ruby when to do this, and we’ll let it do it every 15 seconds.

To set this up for RSpec create a file spec/support/deferred_garbage_collection.rb:

 1class DeferredGarbageCollection
 2
 3  DEFERRED_GC_THRESHOLD = (ENV['DEFER_GC'] || 15.0).to_f
 4
 5  @@last_gc_run = Time.now
 6
 7  def self.start
 8    GC.disable if DEFERRED_GC_THRESHOLD > 0
 9  end
10
11  def self.reconsider
12    if DEFERRED_GC_THRESHOLD > 0 && Time.now - @@last_gc_run >= DEFERRED_GC_THRESHOLD
13      GC.enable
14      GC.start
15      GC.disable
16      @@last_gc_run = Time.now
17    end
18  end
19end

Next, add the following to your spec/spec_helper.rb so rspec will use our deferred garbage collection.

1config.before(:all) do
2  DeferredGarbageCollection.start
3end
4
5config.after(:all) do
6  DeferredGarbageCollection.reconsider
7end

Now, when you run rake spec you should see a nice speed increase. Try to alter the threshold value a bit to see what gives your best performance:

1DEFER_GC=20 rake spec

Enjoy!