Today I learned 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!
~ 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
class DeferredGarbageCollection DEFERRED_GC_THRESHOLD = (ENV['DEFER_GC'] || 15.0).to_f @@last_gc_run = Time.now def self.start GC.disable if DEFERRED_GC_THRESHOLD > 0 end def self.reconsider if DEFERRED_GC_THRESHOLD > 0 && Time.now - @@last_gc_run >= DEFERRED_GC_THRESHOLD GC.enable GC.start GC.disable @@last_gc_run = Time.now end end end
Next, add the following to your
spec/spec_helper.rb so rspec will use our deferred garbage collection.
config.before(:all) do DeferredGarbageCollection.start end config.after(:all) do DeferredGarbageCollection.reconsider end
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:
DEFER_GC=20 rake spec
If you're seeing this message you've probably enabled some form of adblocker. I respect that.
I use this space to show recommended books on Amazon.com in relation to the post you just read. This generates a small income that allows me to buy a book every now and then.