From 52498ccafd718975dc7ad8df2bf7f4a9614a239d Mon Sep 17 00:00:00 2001 From: Jonathan Hefner Date: Sat, 4 May 2019 12:54:28 -0500 Subject: Avoid extra allocation in String#from and #to Removes unnecessary Range object allocations for a significant speed-up. String#from Comparison: new: 3378594.0 i/s old: 2380129.8 i/s - 1.42x slower String#to Comparison: new: 2866175.7 i/s old: 2304406.4 i/s - 1.24x slower --- activesupport/lib/active_support/core_ext/string/access.rb | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/core_ext/string/access.rb b/activesupport/lib/active_support/core_ext/string/access.rb index 4ca24028b0..4894193665 100644 --- a/activesupport/lib/active_support/core_ext/string/access.rb +++ b/activesupport/lib/active_support/core_ext/string/access.rb @@ -44,7 +44,7 @@ class String # str.from(0).to(-1) # => "hello" # str.from(1).to(-2) # => "ell" def from(position) - self[position..-1] + self[position, length] end # Returns a substring from the beginning of the string to the given position. @@ -61,7 +61,8 @@ class String # str.from(0).to(-1) # => "hello" # str.from(1).to(-2) # => "ell" def to(position) - self[0..position] + position = [position + length, -1].max if position < 0 + self[0, position + 1] end # Returns the first character. If a limit is supplied, returns a substring -- cgit v1.2.3