Created
October 19, 2016 20:09
-
-
Save LeFnord/64ca380bb262ddf44f69f73fae337951 to your computer and use it in GitHub Desktop.
ruby memoization benchmarks
This file contains 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 A | |
def name | |
@name ||= begin | |
rand | |
end | |
end | |
end | |
class B | |
def name | |
return(@name) if defined?(@name) | |
@name = rand | |
end | |
end | |
class C | |
def name | |
def self.name | |
@name | |
end | |
@name = rand | |
end | |
end | |
class D | |
def name | |
class << self | |
def name | |
@name | |
end | |
end | |
@name = rand | |
end | |
end | |
m = 1_000 | |
n = 100_000 | |
Benchmark.bm(2) do |x| | |
x.report("A:") { m.times { k = A.new; n.times { k.name } } } | |
x.report("B:") { m.times { k = B.new; n.times { k.name } } } | |
x.report("C:") { m.times { k = C.new; n.times { k.name } } } | |
x.report("D:") { m.times { k = D.new; n.times { k.name } } } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
outcome one my MBP13" (2011, 2.7GHz, Core i7, 8GB),
updates 2020 MBP13" (2017, 3.5GHz, Core i7, 16GB)
updates 2022 MBP13" (2022, M2, 26GB)