Skip to content

Instantly share code, notes, and snippets.

@Bodacious
Created August 6, 2014 11:29
Show Gist options
  • Select an option

  • Save Bodacious/5c8b2dcd17c21db158f7 to your computer and use it in GitHub Desktop.

Select an option

Save Bodacious/5c8b2dcd17c21db158f7 to your computer and use it in GitHub Desktop.
Benchmarking Memoizing of Ruby Methods
require 'benchmark'
class MyClassWithStuff
DEFAULT_VALS = { one: '1' }
def memoized_fetch
@value ||= DEFAULT_VALS[:one]
end
def straight_fetch
DEFAULT_VALS[:one]
end
end
TIMES = 10000
CALL_TIMES = 1000
Benchmark.bmbm do |test|
test.report("Memoized") do
TIMES.times do
instance = MyClassWithStuff.new
CALL_TIMES.times { |i| instance.memoized_fetch }
end
end
test.report("Lookup") do
TIMES.times do
instance = MyClassWithStuff.new
CALL_TIMES.times { |i| instance.straight_fetch }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment