Skip to content

Commit 0e20882

Browse files
authored
Merge pull request #145 from styd/remove-extra-spaces
Remove extra spaces (or other contiguous chars)
2 parents 838a18c + d99f251 commit 0e20882

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1138,6 +1138,24 @@ String#chomp'string': 2803443.5 i/s
11381138
String#sub/regexp/: 660508.7 i/s - 4.24x slower
11391139
```
11401140

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+
11411159

11421160
### Range
11431161

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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

0 commit comments

Comments
 (0)