Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Benchmark local var caching vs direct method access
require 'benchmark'
require 'active_support/all'
Source = Struct.new(:value, keyword_init: true)
def local_var_test(source)
value = source.value
return if value.nil?
value
end
def direct_test(source)
return if source.value.nil?
source.value
end
source = Source.new(value: "value")
n = 100_000
Benchmark.bmbm(15) do |x|
x.report("local var") { n.times { local_var_test(source) } }
x.report("direct") { n.times { direct_test(source) } }
end
# >> user system total real
# >> local var 0.006867 0.000004 0.006871 ( 0.006869)
# >> direct 0.007748 0.000002 0.007750 ( 0.007748)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.