aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport
diff options
context:
space:
mode:
authorJonathan Hefner <jonathan@hefner.pro>2019-05-04 12:54:28 -0500
committerJonathan Hefner <jonathan@hefner.pro>2019-05-05 11:53:20 -0500
commit52498ccafd718975dc7ad8df2bf7f4a9614a239d (patch)
tree4fd8204ceab1526df8f754d30e6d378362d4d1a3 /activesupport
parent9b0e632def6a66bbd0c0aba8531b2a173f7c3064 (diff)
downloadrails-52498ccafd718975dc7ad8df2bf7f4a9614a239d.tar.gz
rails-52498ccafd718975dc7ad8df2bf7f4a9614a239d.tar.bz2
rails-52498ccafd718975dc7ad8df2bf7f4a9614a239d.zip
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
Diffstat (limited to 'activesupport')
-rw-r--r--activesupport/lib/active_support/core_ext/string/access.rb5
1 files changed, 3 insertions, 2 deletions
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