Skip to content

Commit

Permalink
20% faster try
Browse files Browse the repository at this point in the history
Following up on #33747, this takes things a step further by pulling out
the method name from the arguments array, letting us skip an allocation
in the case where there are no arguments -- notably, this also no longer
*requires* the splat to be an array, allowing us to benefit from
optimizations in Jruby (and maybe MRI in the future) of skipping the
array allocation entirely.

Benchmark results:

```
Warming up --------------------------------------
                 old   179.987k i/100ms
                 new   199.201k i/100ms
Calculating -------------------------------------
                 old      3.029M (± 1.6%) i/s -     15.299M in   5.052417s
                 new      3.657M (± 1.2%) i/s -     18.326M in   5.012648s

Comparison:
                 new:  3656620.7 i/s
                 old:  3028848.3 i/s - 1.21x  slower
```
  • Loading branch information
sgrif committed Aug 29, 2018
1 parent cc81cd3 commit 0f462da
Showing 1 changed file with 7 additions and 8 deletions.
15 changes: 7 additions & 8 deletions activesupport/lib/active_support/core_ext/object/try.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,27 @@

module ActiveSupport
module Tryable #:nodoc:
def try(*a, &b)
return unless a.empty? || respond_to?(a.first)
if a.empty? && block_given?
def try(method_name = nil, *args, &b)
if method_name.nil? && block_given?
if b.arity == 0
instance_eval(&b)
else
yield self
end
else
public_send(*a, &b)
elsif respond_to?(method_name)
public_send(method_name, *args, &b)
end
end

def try!(*a, &b)
if a.empty? && block_given?
def try!(method_name = nil, *args, &b)
if method_name.nil? && block_given?
if b.arity == 0
instance_eval(&b)
else
yield self
end
else
public_send(*a, &b)
public_send(method_name, *args, &b)
end
end
end
Expand Down

0 comments on commit 0f462da

Please sign in to comment.