diff options
author | Ryuta Kamizono <kamipo@gmail.com> | 2019-07-28 17:16:03 +0900 |
---|---|---|
committer | Ryuta Kamizono <kamipo@gmail.com> | 2019-07-28 17:16:03 +0900 |
commit | 71e41a5b9495ba6ebe3cdf1e10afa27bcc0db208 (patch) | |
tree | bc3328a59dc856217ce831ea9099d7bee8aac1f7 /activesupport/lib/active_support/string_inquirer.rb | |
parent | 715dad107b5cce4f09065b4f6b84641f6d18f028 (diff) | |
download | rails-71e41a5b9495ba6ebe3cdf1e10afa27bcc0db208.tar.gz rails-71e41a5b9495ba6ebe3cdf1e10afa27bcc0db208.tar.bz2 rails-71e41a5b9495ba6ebe3cdf1e10afa27bcc0db208.zip |
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
```
Diffstat (limited to 'activesupport/lib/active_support/string_inquirer.rb')
0 files changed, 0 insertions, 0 deletions