diff options
author | Sean Griffin <sean@seantheprogrammer.com> | 2018-08-29 12:39:27 -0600 |
---|---|---|
committer | Sean Griffin <sean@seantheprogrammer.com> | 2018-08-29 12:42:01 -0600 |
commit | 0f462da85dbd7b6ad6c1d79858b8aa6f28ca9638 (patch) | |
tree | 752d29be9d0a033223c2a402041ca08ba328a04a /activesupport/lib | |
parent | cc81cd359c82bfba27388237a455fc345dce3c9f (diff) | |
download | rails-0f462da85dbd7b6ad6c1d79858b8aa6f28ca9638.tar.gz rails-0f462da85dbd7b6ad6c1d79858b8aa6f28ca9638.tar.bz2 rails-0f462da85dbd7b6ad6c1d79858b8aa6f28ca9638.zip |
20% faster `try`
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
```
Diffstat (limited to 'activesupport/lib')
-rw-r--r-- | activesupport/lib/active_support/core_ext/object/try.rb | 15 |
1 files changed, 7 insertions, 8 deletions
diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb index bd841771ce..aa6896af32 100644 --- a/activesupport/lib/active_support/core_ext/object/try.rb +++ b/activesupport/lib/active_support/core_ext/object/try.rb @@ -4,28 +4,27 @@ require "delegate" 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 |