DEV Community

Alexander Budchanov
Alexander Budchanov

Posted on • Originally published at jetrockets.pro

4 3

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
Enter fullscreen mode Exit fullscreen mode
                                          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)
Enter fullscreen mode Exit fullscreen mode

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post →

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post