Last active
June 18, 2019 20:35
-
-
Save rmm5t/5010220fd30993517bed874fea1f7bfa to your computer and use it in GitHub Desktop.
Benchmark local var caching vs direct method access
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 '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