Skip to content

Instantly share code, notes, and snippets.

@hopsoft
Last active June 11, 2020 14:27
Show Gist options
  • Save hopsoft/ae361319c54bbcb4f8e2 to your computer and use it in GitHub Desktop.
Save hopsoft/ae361319c54bbcb4f8e2 to your computer and use it in GitHub Desktop.
Ruby 2.3 safe navigation `&.` vs Active Support's try
require "benchmark"
require "active_support/all"
Benchmark.bm do |x|
count = 1_000_000
label_size = 20
x.report "check for nil:".rjust(label_size) do
count.times { nil && nil.length }
end
x.report "check respond_to:".rjust(label_size) do
count.times { nil.length if nil.respond_to?(:length) }
end
x.report "rescue:".rjust(label_size) do
count.times { nil.length rescue nil }
end
x.report "active_support try:".rjust(label_size) do
count.times { nil.try(:length) }
end
x.report "safe navigation:".rjust(label_size) do
count.times { nil&.length }
end
end
user system total real
check for nil: 0.040000 0.000000 0.040000 ( 0.040230)
check respond_to: 0.100000 0.000000 0.100000 ( 0.101780)
rescue: 2.080000 0.020000 2.100000 ( 2.103482)
active_support try: 0.150000 0.000000 0.150000 ( 0.151765)
safe navigation: 0.040000 0.000000 0.040000 ( 0.040369)
strategy time degradation
check for nil 0.040230 1.00
check respond_to 0.101780 2.529
rescue 2.103482 52.286
active_support try 0.151765 3.772
safe navigation 0.040369 1.003
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment