Created
August 6, 2014 11:29
-
-
Save Bodacious/5c8b2dcd17c21db158f7 to your computer and use it in GitHub Desktop.
Benchmarking Memoizing of Ruby Methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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