1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Performance improvement for String#to

```ruby
class String
  def to1(position)
    position = [position + length, -1].max if position < 0
    self[0, position + 1]
  end

  def to2(position)
    position += size if position < 0
    self[0, position + 1] || +""
  end
end

Benchmark.ips do |x|
  x.report("'foo'.to(1)")  { 'foo'.to(1) }
  x.report("'foo'.to1(1)") { 'foo'.to1(1) }
  x.report("'foo'.to2(1)") { 'foo'.to2(1) }

  x.report("'foo'.to(-1)")  { 'foo'.to(-1) }
  x.report("'foo'.to1(-1)") { 'foo'.to1(-1) }
  x.report("'foo'.to2(-1)") { 'foo'.to2(-1) }

  x.report("'foo'.to(-10)")  { 'foo'.to(-10) }
  x.report("'foo'.to1(-10)") { 'foo'.to1(-10) }
  x.report("'foo'.to2(-10)") { 'foo'.to2(-10) }
end
```

Result:

```
Warming up --------------------------------------
         'foo'.to(1)   199.859k i/100ms
        'foo'.to1(1)   220.293k i/100ms
        'foo'.to2(1)   221.522k i/100ms
        'foo'.to(-1)   205.032k i/100ms
       'foo'.to1(-1)   195.837k i/100ms
       'foo'.to2(-1)   214.975k i/100ms
       'foo'.to(-10)   214.331k i/100ms
      'foo'.to1(-10)   182.666k i/100ms
      'foo'.to2(-10)   224.696k i/100ms
Calculating -------------------------------------
         'foo'.to(1)      4.685M (± 4.2%) i/s -     23.583M in   5.042568s
        'foo'.to1(1)      5.233M (± 5.8%) i/s -     26.215M in   5.026778s
        'foo'.to2(1)      5.180M (± 5.7%) i/s -     25.918M in   5.020735s
        'foo'.to(-1)      4.253M (± 7.0%) i/s -     21.323M in   5.043133s
       'foo'.to1(-1)      4.438M (±11.2%) i/s -     21.934M in   5.025751s
       'foo'.to2(-1)      4.716M (± 9.8%) i/s -     23.432M in   5.028088s
       'foo'.to(-10)      4.678M (± 9.5%) i/s -     23.148M in   5.007379s
      'foo'.to1(-10)      4.428M (± 5.1%) i/s -     22.103M in   5.005155s
      'foo'.to2(-10)      5.243M (± 4.6%) i/s -     26.289M in   5.024695s
```
This commit is contained in:
Ryuta Kamizono 2019-07-28 17:16:03 +09:00
parent 715dad107b
commit 71e41a5b94
3 changed files with 1 additions and 3 deletions

View file

@ -62,7 +62,7 @@ class String
# str.from(1).to(-2) # => "ell"
def to(position)
position += size if position < 0
self[0, position + 1].to_s
self[0, position + 1] || +""
end
# Returns the first character. If a limit is supplied, returns a substring

View file

@ -793,7 +793,6 @@ module ActiveSupport #:nodoc:
end
private
# Returns the original name of a class or module even if `name` has been
# overridden.
def real_mod_name(mod)

View file

@ -44,7 +44,6 @@ module ActiveSupport
end
private
def build_rotation(previous_value, _options)
self.class.new(previous_value)
end