Skip to content

Instantly share code, notes, and snippets.

@dschneider
Created November 25, 2012 17:55
Show Gist options
  • Save dschneider/4144563 to your computer and use it in GitHub Desktop.
Save dschneider/4144563 to your computer and use it in GitHub Desktop.
Deferred Garbage Collection for speeding up unit and integration tests
# Public: This class contains methods for deferred garbage collection which
# improves the time consumption of integration and unit tests.
class DeferredGarbageCollection
# Public: The time threshold used by the deferred garbage collection. It's
# either set as an environment variable or defaults to 5 seconds.
GC_THRESHOLD = (ENV['DEFER_GC'] || 5.0).to_f
# Public: The last time the GC has run.
@@last_gc_run = Time.now
# Public: Starts the deferred Garbage Collection.
def self.start
GC.disable if GC_THRESHOLD > 0
end
# Public: Checks if last run time exceeds the value of the time threshold and
# enables Garbage Collection for a short cleanup. After that Garbage
# Collection is deferred again.
def self.reconsider
if GC_THRESHOLD > 0 && Time.now - @@last_gc_run >= GC_THRESHOLD
GC.enable
GC.start
GC.disable
@@last_gc_run = Time.now
end
end
end
# PUT THIS IN YOUR SPEC HELPER
config.before(:all) do
DeferredGarbageCollection.start
end
config.after(:all) do
DeferredGarbageCollection.reconsider
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment