Last active
December 11, 2017 08:04
-
-
Save ivan-leschinsky/d0e0ea859b9ac009ee7c to your computer and use it in GitHub Desktop.
Benchmarking ruby delegate
This file contains 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 aa | |
42^3344 | |
end | |
end | |
class B | |
def aa | |
a.aa | |
end | |
def a | |
@a ||= A.new | |
end | |
end | |
class C | |
delegate :aa, to: :a | |
def a | |
@a ||= A.new | |
end | |
end | |
time = Benchmark.measure do | |
10000000.times { B.new.aa } | |
end | |
puts "B: #{time}" | |
time = Benchmark.measure do | |
10000000.times { C.new.aa } | |
end | |
puts "C: #{time}" | |
# => B: 9.170000 0.030000 9.200000 ( 9.257936) | |
# => C: 11.480000 0.020000 11.500000 ( 11.548755) |
This file contains 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 aa | |
222**222 | |
end | |
end | |
class B | |
def aa | |
a.aa | |
end | |
def a | |
@a ||= A.new | |
end | |
end | |
class C | |
delegate :aa, to: :a | |
def a | |
@a ||= A.new | |
end | |
end | |
time = Benchmark.measure do | |
1000000.times { [*nil] } | |
end | |
puts "B: #{time}" | |
time = Benchmark.measure do | |
1000000.times { C.new.aa } | |
end | |
puts "C: #{time}" | |
# => B: 6.440000 0.110000 6.550000 ( 6.616437) | |
# => C: 6.770000 0.040000 6.810000 ( 6.848812) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment