Skip to content

Commit d64e875

Browse files
committed
Merge pull request #47 from bquorning/sub-vs-chomp
String#chomp can be faster than String#sub
2 parents a55d178 + 20f3661 commit d64e875

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -837,6 +837,25 @@ String#gsub!'string': 481183.5 i/s - 2.52x slower
837837
String#gsub!/regexp/: 342003.8 i/s - 3.55x slower
838838
```
839839

840+
##### `String#sub` vs `String#chomp` [code](code/string/sub-vs-chomp.rb)
841+
842+
Note that this can only be used for removing characters from the end of a string.
843+
844+
```
845+
$ ruby -v code/string/sub-vs-chomp.rb
846+
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin13]
847+
Calculating -------------------------------------
848+
String#sub/regexp/ 38.068k i/100ms
849+
String#chomp'string' 78.284k i/100ms
850+
-------------------------------------------------
851+
String#sub/regexp/ 560.625k (±17.1%) i/s - 2.703M
852+
String#chomp'string' 2.704M (±18.6%) i/s - 12.839M
853+
854+
Comparison:
855+
String#chomp'string': 2703881.6 i/s
856+
String#sub/regexp/: 560625.4 i/s - 4.82x slower
857+
```
858+
840859
##### `attr_accessor` vs `getter and setter` [code](code/general/attr-accessor-vs-getter-and-setter.rb)
841860

842861
> https://www.omniref.com/ruby/2.2.0/files/method.h?#annotation=4081781&line=47

code/string/sub-vs-chomp.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
require 'benchmark/ips'
2+
3+
SLUG = 'YourSubclassType'
4+
5+
def slow
6+
SLUG.sub(/Type$/, '')
7+
end
8+
9+
def fast
10+
SLUG.chomp('Type')
11+
end
12+
13+
Benchmark.ips do |x|
14+
x.report('String#sub/regexp/') { slow }
15+
x.report("String#chomp'string'") { fast }
16+
x.compare!
17+
end

0 commit comments

Comments
 (0)