Last active
March 8, 2017 19:11
-
-
Save danielevans/e4d0269b3cc849b164c7eac60b8e038c to your computer and use it in GitHub Desktop.
Speed of delegation in ruby
This file contains hidden or 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 "active_support/core_ext/module" | |
require 'benchmark' | |
class Test | |
def initialize | |
@time = Time.now | |
end | |
delegate :to_i, to: :@time, prefix: :ar | |
def two | |
@time.to_i | |
end | |
define_method :three do | |
@time.to_i | |
end | |
class_eval <<CHUNK | |
def #{"four"} | |
@#{"time"}.to_i | |
end | |
CHUNK | |
end | |
instance = Test.new | |
iterations = 10_000_000 | |
Benchmark.bm(10) do |bm| | |
bm.report("delegated") { iterations.times { instance.ar_to_i } } | |
bm.report("defined") { iterations.times { instance.two } } | |
bm.report("def_meth") { iterations.times { instance.three } } | |
bm.report("eval") { iterations.times { instance.four } } | |
end | |
# user system total real | |
# delegated 2.770000 0.010000 2.780000 ( 2.806770) | |
# defined 1.950000 0.010000 1.960000 ( 1.966655) | |
# def_meth 2.450000 0.020000 2.470000 ( 2.516374) | |
# eval 1.890000 0.000000 1.890000 ( 1.900834) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment