I am curious about performance for Rails Object#presence vs Object#try - here is result
Comments
Why would you want to compare these methods? They do absolutely different things.
Yuri Smirnov —
In ruby 2.3+ the ‘&.’ operator is faster still.
user system total real
seller && seller.name 0.000005 0.000001 0.000006 ( 0.000005)
seller&.name 0.000003 0.000001 0.000004 ( 0.000003)
seller.try(:name) 0.000006 0.000001 0.000007 ( 0.000006)
seller.name.presence 0.000006 0.000001 0.000007 ( 0.000006)
Andrew Nutter-Upham —
I agree with Yuri. #try and #presence have entirely different use cases. Comparing their performance is pretty pointless.
#try is to simplify calling methods on objects which might be nil, for example seller.phone.try(:strip) - (no fail if phone is nil) vs seller.phone.presence.strip (fails if phone is nil).
The use case of #presence is to simplify default values for empty or nil attributes like in your example, seller.name.presence || "-".
Comments
Why would you want to compare these methods? They do absolutely different things.
In ruby 2.3+ the ‘&.’ operator is faster still.
user system total real seller && seller.name 0.000005 0.000001 0.000006 ( 0.000005) seller&.name 0.000003 0.000001 0.000004 ( 0.000003) seller.try(:name) 0.000006 0.000001 0.000007 ( 0.000006) seller.name.presence 0.000006 0.000001 0.000007 ( 0.000006)
I agree with Yuri.
#try
and#presence
have entirely different use cases. Comparing their performance is pretty pointless.#try
is to simplify calling methods on objects which might be nil, for exampleseller.phone.try(:strip)
- (no fail if phone is nil) vsseller.phone.presence.strip
(fails if phone is nil).The use case of
#presence
is to simplify default values for empty or nil attributes like in your example,seller.name.presence || "-"
.Hope this helps other readers.
Post a comment