Skip to content

Commit bb513b8

Browse files
committed
Fix performance slowdown in Ruby 2.7+
In rails#34068 I introduced code that improved performance in Ruby 2.5. But recently @jeremyevans pointed out that it made code slower in 2.7+ which Rails targets https://gist.github.com/jeremyevans/40675ac1f69b4ac405d3c6ba060cdd35. Here's the twitter thread https://twitter.com/jeremyevans0/status/1414731600693108737. This change essentially reverts rails#34068 ``` $ cat scratch.rb class FooCurrent def try(_method_name = nil, *) nil end end class FooUpdated def try(*) nil end end require 'benchmark/ips' foo_updated = FooUpdated.new foo_current = FooCurrent.new Benchmark.ips do |x| x.report("updated") { foo_updated.try(:anything) } x.report("current") { foo_current.try(:anything) } x.compare! end $ ruby -v ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-darwin19] $ ruby scratch.rb Warming up -------------------------------------- updated 854.461k i/100ms current 687.183k i/100ms Calculating ------------------------------------- updated 8.418M (± 2.1%) i/s - 42.723M in 5.077403s current 6.619M (± 9.6%) i/s - 32.985M in 5.048477s Comparison: updated: 8418315.3 i/s current: 6619074.1 i/s - 1.27x (± 0.00) slower ```
1 parent 359efef commit bb513b8

File tree

1 file changed

+9
-9
lines changed
  • activesupport/lib/active_support/core_ext/object

1 file changed

+9
-9
lines changed

activesupport/lib/active_support/core_ext/object/try.rb

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,28 +4,28 @@
44

55
module ActiveSupport
66
module Tryable #:nodoc:
7-
def try(method_name = nil, *args, &block)
8-
if method_name.nil? && block_given?
7+
def try(*args, &block)
8+
if args.empty? && block_given?
99
if block.arity == 0
1010
instance_eval(&block)
1111
else
1212
yield self
1313
end
14-
elsif respond_to?(method_name)
15-
public_send(method_name, *args, &block)
14+
elsif respond_to?(args.first)
15+
public_send(*args, &block)
1616
end
1717
end
1818
ruby2_keywords(:try)
1919

20-
def try!(method_name = nil, *args, &block)
21-
if method_name.nil? && block_given?
20+
def try!(*args, &block)
21+
if args.empty? && block_given?
2222
if block.arity == 0
2323
instance_eval(&block)
2424
else
2525
yield self
2626
end
2727
else
28-
public_send(method_name, *args, &block)
28+
public_send(*args, &block)
2929
end
3030
end
3131
ruby2_keywords(:try!)
@@ -145,14 +145,14 @@ class NilClass
145145
#
146146
# With +try+
147147
# @person.try(:children).try(:first).try(:name)
148-
def try(_method_name = nil, *)
148+
def try(*)
149149
nil
150150
end
151151

152152
# Calling +try!+ on +nil+ always returns +nil+.
153153
#
154154
# nil.try!(:name) # => nil
155-
def try!(_method_name = nil, *)
155+
def try!(*)
156156
nil
157157
end
158158
end

0 commit comments

Comments
 (0)