Skip to content

Instantly share code, notes, and snippets.

@jnicklas
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnicklas/170814b6150219ec61f9 to your computer and use it in GitHub Desktop.
Save jnicklas/170814b6150219ec61f9 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
require 'memoit'
class Tested
def manual
@manual ||= 123
end
def manual_hash(key)
@manual_hash ||= {}
@manual_hash[key] ||= 123 + key
end
memoize def memoit
123
end
memoize def memoit_hash(key)
key + 123
end
end
tested = Tested.new
Benchmark.ips do |x|
x.config(:time => 5, :warmup => 2)
x.report("manual") do
tested.manual
end
x.report("memoit") do
tested.memoit
end
x.compare!
end
Benchmark.ips do |x|
x.config(:time => 5, :warmup => 2)
x.report("manual_hash_fixed") do
tested.manual_hash(55)
end
x.report("memoit_hash_fixed") do
tested.memoit_hash(55)
end
x.compare!
end
Benchmark.ips do |x|
x.config(:time => 5, :warmup => 2)
x.report("manual_hash_random") do
tested.manual_hash(rand(100_000_000_000))
end
x.report("memoit_hash_random") do
tested.memoit_hash(rand(100_000_000_000))
end
x.compare!
end
Calculating -------------------------------------
manual 121.076k i/100ms
memoit 82.766k i/100ms
-------------------------------------------------
manual 6.629M (± 1.3%) i/s - 33.175M
memoit 2.487M (± 0.8%) i/s - 12.498M
Comparison:
manual: 6628909.4 i/s
memoit: 2486543.8 i/s - 2.67x slower
Calculating -------------------------------------
manual_hash_fixed 108.751k i/100ms
memoit_hash_fixed 58.607k i/100ms
-------------------------------------------------
manual_hash_fixed 5.103M (± 1.3%) i/s - 25.556M
memoit_hash_fixed 1.390M (± 1.2%) i/s - 6.974M
Comparison:
manual_hash_fixed: 5103490.5 i/s
memoit_hash_fixed: 1390457.4 i/s - 3.67x slower
Calculating -------------------------------------
manual_hash_random 53.694k i/100ms
memoit_hash_random 32.026k i/100ms
-------------------------------------------------
manual_hash_random 1.080M (±14.1%) i/s - 5.208M
memoit_hash_random 529.031k (±12.7%) i/s - 2.594M
Comparison:
manual_hash_random: 1080078.4 i/s
memoit_hash_random: 529031.2 i/s - 2.04x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment