Which is faster? Inline rescue
, or classic branching based on the respond_to?
method? Let’s face them off.
ding
Download this, then run like so:
$ ruby test_rescue.rb success respond_to
0.947819 seconds
$ ruby test_rescue.rb success rescue
0.575646 seconds
$ ruby test_rescue.rb failure respond_to
0.789487 seconds
$ ruby test_rescue.rb failure rescue
16.1751 seconds
This suggests that a clean rescue
path is about twice as fast as a successful respond_to?
condition. But a raised rescue
is 20 times slower than a failed respond_to?
.
a champion! sort of
Excusing my slipshod math and neglect of all other relevant factors, this means that in time-critical code paths we should use respond_to?
unless the path is predicted to fail less than 2.5% of the time. So it depends.