Skip to content

Instantly share code, notes, and snippets.

@supremebeing7
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save supremebeing7/edd9c47660e102efb286 to your computer and use it in GitHub Desktop.
Save supremebeing7/edd9c47660e102efb286 to your computer and use it in GitHub Desktop.
Get rid of extraneous conditionals
# If @user does not exist or is nil...
@user.name
# => throws an exception, "undefined method 'name' for NilClass"
# The easy fix is to solve with a conditional:
@user.name if @user
# The more fun (and probably dirtier) way is to use the #try method:
@user.try(:name)
# This accomplishes the same thing as using the conditional, but it's shorter and reads better.
# Warning: Using #try is consistently a fraction of a second slower than using the conditional.
# user1 = User.create(name: 'Mark')
# user2 = nil
Benchmark.bm do |x|
x.report { user1.name if user1 }
x.report { user1.try(:name) }
x.report { user2.name if user2 }
x.report { user2.try(:name) }
end
user system total real
0.000000 0.000000 0.000000 ( 0.000020)
0.000000 0.000000 0.000000 ( 0.000067)
0.000000 0.000000 0.000000 ( 0.000002)
0.000000 0.000000 0.000000 ( 0.000003)
=> [#<Benchmark::Tms:0x000000045cc7c8
@cstime=0.0,
@cutime=0.0,
@label="",
@real=2.0046e-05,
@stime=0.0,
@total=0.0,
@utime=0.0>,
#<Benchmark::Tms:0x000000045ca4f0
@cstime=0.0,
@cutime=0.0,
@label="",
@real=6.7324e-05,
@stime=0.0,
@total=0.0,
@utime=0.0>,
#<Benchmark::Tms:0x000000045c8e70
@cstime=0.0,
@cutime=0.0,
@label="",
@real=1.99e-06,
@stime=0.0,
@total=0.0,
@utime=0.0>,
#<Benchmark::Tms:0x000000045c2368
@cstime=0.0,
@cutime=0.0,
@label="",
@real=3.396e-06,
@stime=0.0,
@total=0.0,
@utime=0.0>]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment