Skip to content

Instantly share code, notes, and snippets.

@plukevdh
Last active August 29, 2015 14:16
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 plukevdh/a8bebde934cec3a2d203 to your computer and use it in GitHub Desktop.
Save plukevdh/a8bebde934cec3a2d203 to your computer and use it in GitHub Desktop.
benchmark ruby method delegation
require 'benchmark/ips'
class Bass
def initialize(hash)
@hash = hash
end
end
class Testing < Bass
def []=(key, value)
@hash[key] = value
end
def [](key)
@hash[key]
end
end
class Forwarding < Bass
extend Forwardable
def_delegators :@hash, :[]=, :[]
end
class Missinged < Bass
def method_missing(meth, *args)
if @hash.respond_to? meth
@hash.send(meth, *args)
else
super
end
end
end
test = Testing.new one: 1, two: 2
fwd = Forwarding.new one: 1, two: 2
msg = Missinged.new one: 1, two: 2
Benchmark.ips do |x|
x.config(:time => 5, :warmup => 2)
x.report("method") { test[:two] }
x.report("forward") { fwd[:two] }
x.report("missing") { msg[:two] }
x.compare!
end
Benchmark.ips do |x|
x.config(:time => 5, :warmup => 2)
x.report("method") { test[:one] = 3 }
x.report("forward") { fwd[:one] = 3 }
x.report("missing") { msg[:one] = 3 }
x.compare!
end
Calculating -------------------------------------
method 143.572k i/100ms
forward 110.827k i/100ms
missing 103.273k i/100ms
-------------------------------------------------
method 6.891M (± 6.6%) i/s - 34.314M
forward 3.178M (± 4.2%) i/s - 15.959M
missing 2.583M (± 4.2%) i/s - 12.909M
Comparison:
method: 6890944.2 i/s
forward: 3177632.4 i/s - 2.17x slower
missing: 2582692.1 i/s - 2.67x slower
Calculating -------------------------------------
method 142.653k i/100ms
forward 110.198k i/100ms
missing 101.819k i/100ms
-------------------------------------------------
method 6.184M (± 5.9%) i/s - 30.956M
forward 2.916M (± 5.8%) i/s - 14.546M
missing 2.387M (± 5.8%) i/s - 11.913M
Comparison:
method: 6183999.6 i/s
forward: 2916127.8 i/s - 2.12x slower
missing: 2387408.8 i/s - 2.59x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment