-
-
Save wteuber/6e46e0d70b89872530fd0090b43cc3db to your computer and use it in GitHub Desktop.
ruby memoization benchmarks
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 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 | |
class Z | |
def name | |
@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 } } } | |
x.report("Z:") { m.times { k = Z.new; n.times { k.name } } } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment