-
-
Notifications
You must be signed in to change notification settings - Fork 274
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Optimize hash access by safe-navigating Hash#dig
#654
Optimize hash access by safe-navigating Hash#dig
#654
Conversation
Benchmarking Benchmark.driver do |x|
x.prelude %{
hash = {a: {b: 5}}
}
x.report("[][]", %{hash[:a][:b]})
x.report("dig", %{hash.dig(:a, :b)})
end Result on 2.6.5:
So I wouldn't use |
I see.., however with specific focus on line Benchmark.driver do |x|
x.prelude %{
options = {}
}
x.report("[][]", %{options[:ial][:refs] rescue nil})
x.report("dig", %{options.dig(:ial, :refs)})
end
Benchmark.driver do |x|
x.prelude %{
options = {ial: {}}
}
x.report("[][]", %{options[:ial][:refs] rescue nil})
x.report("dig", %{options.dig(:ial, :refs)})
end With Ruby 2.4 on Windows:
I concede that |
Ah, sorry, this is my fault, posted this between things... What I meant with my benchmark comment was that the additional changes are not needed, i.e. the ones you meant with "The remaining changes are for consistency." |
Thank you! |
By using
Hash#dig
in tandem with the safe navigation operator (both from Ruby 2.3), the logic doesn't need torescue and return nil
(therefore faster and avoids allocatingThread::Backtrace
) nor have to assign to[]
(on every call) to check if an object is included..Note: Only lines explicitly that
rescue and return nil
are patched in this pull request.