Skip to content

Instantly share code, notes, and snippets.

@LeFnord
Created October 19, 2016 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save LeFnord/64ca380bb262ddf44f69f73fae337951 to your computer and use it in GitHub Desktop.
Save LeFnord/64ca380bb262ddf44f69f73fae337951 to your computer and use it in GitHub Desktop.
ruby memoization benchmarks
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
@LeFnord
Copy link
Author

LeFnord commented Oct 19, 2016

outcome one my MBP13" (2011, 2.7GHz, Core i7, 8GB),

  • ruby 2.3.1p112
#          user     system      total        real
# A:  12.840000   0.060000  12.900000 ( 13.021907)
# B:  12.730000   0.030000  12.760000 ( 12.803362)
# C:   8.750000   0.020000   8.770000 (  8.777640)
# D:   8.670000   0.030000   8.700000 (  8.711447)
  • ruby 2.4.0preview2
#          user     system      total        real
# A:  12.330000   0.030000  12.360000 ( 12.390254)
# B:  12.460000   0.030000  12.490000 ( 12.514525)
# C:   8.630000   0.030000   8.660000 (  8.659562)
# D:   8.600000   0.020000   8.620000 (  8.637199)

updates 2020 MBP13" (2017, 3.5GHz, Core i7, 16GB)

  • ruby 2.6.5p114
         user     system      total        real
A:   6.621856   0.033449   6.655305 (  6.729829)
B:   6.485719   0.032604   6.518323 (  6.586271)
C:   4.642020   0.022413   4.664433 (  4.707718)
D:   4.662892   0.022654   4.685546 (  4.728444)
  • ruby 2.7.1p83
         user     system      total        real
A:   6.924522   0.028161   6.952683 (  7.009376)
B:   6.726189   0.026435   6.752624 (  6.803138)
C:   4.934192   0.021075   4.955267 (  4.994404)
D:   5.319345   0.027878   5.347223 (  5.661348)

updates 2022 MBP13" (2022, M2, 26GB)

  • ruby 3.1.3p185
         user     system      total        real
A:   4.753816   0.011587   4.765403 (  4.765577)
B:   6.452455   0.019077   6.471532 (  6.471763)
C:   4.560255   0.011599   4.571854 (  4.592428)
D:   4.540045   0.007256   4.547301 (  4.547607)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment