Skip to content

Instantly share code, notes, and snippets.

@timonv
Last active August 29, 2015 14:27
Show Gist options
  • Save timonv/40867ac63bbb7084ef72 to your computer and use it in GitHub Desktop.
Save timonv/40867ac63bbb7084ef72 to your computer and use it in GitHub Desktop.
require 'memoist'
require 'benchmark'
class Normal
def value
1000.times do |i|
123.45 * 3323.2 / i + 1
end
end
def calc
1000.times do |i|
i * value
end
end
end
class Memoized < Normal
def value
@_value ||= super
end
end
class Memoisted < Normal
extend Memoist
memoize :value
end
puts "Without args"
Benchmark.bm do |x|
x.report("normal:") { Normal.new.calc }
x.report("memoized:") { Memoized.new.calc }
x.report("memoisted:"){ Memoisted.new.calc }
end
class Normal
def value(arg)
1000.times do |i|
123.45 * arg / i + 1
end
end
def calc
1000.times do |i|
i * value(5)
end
end
end
class Memoized < Normal
def value(arg)
@_value ||= {}
@_value[arg] ||= super arg
end
end
class Memoisted < Normal
extend Memoist
memoize :value
end
puts "With args: "
Benchmark.bm do |x|
x.report("normal:") { Normal.new.calc }
x.report("memoized:") { Memoized.new.calc }
x.report("memoisted:"){ Memoisted.new.calc }
end
@timonv
Copy link
Author

timonv commented Aug 17, 2015

Results:

Without args
       user     system      total        real
normal:  0.260000   0.000000   0.260000 (  0.260516)
memoized:  0.000000   0.000000   0.000000 (  0.000541)
memoisted:  0.000000   0.000000   0.000000 (  0.002366)
With args: 
       user     system      total        real
normal:  0.260000   0.000000   0.260000 (  0.260472)
memoized:  0.000000   0.000000   0.000000 (  0.000667)
memoisted:  0.240000   0.000000   0.240000 (  0.244774)

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