Skip to content

Instantly share code, notes, and snippets.

@rmm5t
Last active June 18, 2019 23:38
Show Gist options
  • Save rmm5t/430a30e02353e0eb0c55acdc311bf802 to your computer and use it in GitHub Desktop.
Save rmm5t/430a30e02353e0eb0c55acdc311bf802 to your computer and use it in GitHub Desktop.
Benchmark instance variable vs delegation
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