From 0f462da85dbd7b6ad6c1d79858b8aa6f28ca9638 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Wed, 29 Aug 2018 12:39:27 -0600 Subject: 20% faster `try` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 ``` --- activesupport/lib/active_support/core_ext/object/try.rb | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) (limited to 'activesupport') 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 -- cgit v1.2.3