File tree Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -1138,6 +1138,24 @@ String#chomp'string': 2803443.5 i/s
1138
1138
String#sub/regexp/: 660508.7 i/s - 4.24x slower
1139
1139
```
1140
1140
1141
+ ##### Remove extra spaces (or other contiguous characters) [ code] ( code/string/remove-extra-spaces-or-other-chars.rb )
1142
+
1143
+ The code is tested against contiguous spaces but should work for other chars too.
1144
+
1145
+ ```
1146
+ ruby 2.5.0p0 (2017-12-25 revision 61468) [x86_64-linux]
1147
+ Warming up --------------------------------------
1148
+ String#gsub/regex+/ 1.644k i/100ms
1149
+ String#squeeze 24.681k i/100ms
1150
+ Calculating -------------------------------------
1151
+ String#gsub/regex+/ 14.668k (± 5.1%) i/s - 73.980k in 5.056887s
1152
+ String#squeeze 372.910k (± 8.4%) i/s - 1.851M in 5.011881s
1153
+
1154
+ Comparison:
1155
+ String#squeeze: 372910.3 i/s
1156
+ String#gsub/regex+/: 14668.1 i/s - 25.42x slower
1157
+ ```
1158
+
1141
1159
1142
1160
### Range
1143
1161
Original file line number Diff line number Diff line change
1
+ require 'benchmark/ips'
2
+
3
+ PASSAGE = <<~LIPSUM
4
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
5
+ Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
6
+ Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
7
+ Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
8
+ LIPSUM
9
+
10
+ raise unless PASSAGE . gsub ( / +/ , " " ) == PASSAGE . squeeze ( " " )
11
+
12
+ def slow
13
+ PASSAGE . gsub ( / +/ , " " )
14
+ end
15
+
16
+ def fast
17
+ PASSAGE . squeeze ( " " )
18
+ end
19
+
20
+ Benchmark . ips do |x |
21
+ x . report ( 'String#gsub/regex+/' ) { slow }
22
+ x . report ( 'String#squeeze' ) { fast }
23
+ x . compare!
24
+ end
You can’t perform that action at this time.
0 commit comments