Skip to content

Instantly share code, notes, and snippets.

@rmm5t
Last active June 18, 2019 20:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmm5t/5010220fd30993517bed874fea1f7bfa to your computer and use it in GitHub Desktop.
Save rmm5t/5010220fd30993517bed874fea1f7bfa to your computer and use it in GitHub Desktop.
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