Benchmark instance variable vs delegation
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' | |
require 'active_support/all' | |
Source = Struct.new(:value, keyword_init: true) | |
class InstanceVarTest | |
attr_reader :source, :value | |
def initialize(source) | |
@source = source | |
@value = source.value | |
end | |
end | |
# Rails delegate has an extra local var assignment so it can yield improved | |
# error messages | |
class RailsDelegateTest | |
attr_reader :source | |
delegate :value, to: :source | |
def initialize(source) | |
@source = source | |
end | |
end | |
class ManualDelegateTest | |
attr_reader :source | |
def initialize(source) | |
@source = source | |
end | |
def value | |
source.value | |
end | |
end | |
source = Source.new(value: "value") | |
n = 100_000 | |
Benchmark.bmbm(15) do |x| | |
x.report("reader") { n.times { InstanceVarTest.new(source).value } } | |
x.report("rails delegate") { n.times { RailsDelegateTest.new(source).value } } | |
x.report("manual delegate") { n.times { ManualDelegateTest.new(source).value } } | |
end | |
# >> user system total real | |
# >> reader 0.017031 0.000017 0.017048 ( 0.017064) | |
# >> rails delegate 0.023334 0.000005 0.023339 ( 0.023340) | |
# >> manual delegate 0.016949 0.000005 0.016954 ( 0.016954) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment