Safe Navigation vs Try in Rails (Part 2: Performance)


This Note is an extension of Safe Navigation vs Try in Rails (Part 1: Basic Differences)

Method try() comes from Active Support component of Ruby on Rails. Safe Navigation Operator is Ruby native feature.

Let's check performance!


require 'benchmark'



class Foo

  attr_accessor :name

end



foo = Foo.new

bar = nil



Benchmark.bm(35) do |x|

  x.report('Successful access: try(...): ')         { 1_000_000.times { foo.try(:name) } }

  x.report('Successful access: &.: ')               { 1_000_000.times { foo&.name } }

  x.report('Successful access: control sample: ')   { 1_000_000.times { foo.name } }

  x.report('Failed access: try(...): ')             { 1_000_000.times { bar.try(:nonexistent) } }

  x.report('Failed access: safe navigation: ')      { 1_000_000.times { bar&.nonexistent } }

end;nil


                                          user     system      total        real

Successful access: try(...):          0.498216   0.005748   0.503964 (  0.530010)

Successful access: &.:                0.062146   0.000943   0.063089 (  0.069714)

Successful access: control sample:    0.062411   0.001098   0.063509 (  0.069603)

Failed access: try(...):              0.172535   0.004374   0.176909 (  0.194386)

Failed access: safe navigation:       0.054141   0.001029   0.055170 (  0.065502)

Safe navigation is about 7 times faster than method try() for successful navigation and 3 times faster for unsuccessful.


Alexander
Budchanov

Backend Developer at JetRockets

Explore more of JetRockets