Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1138,6 +1138,24 @@ String#chomp'string': 2803443.5 i/s
String#sub/regexp/: 660508.7 i/s - 4.24x slower
```

##### Remove extra spaces (or other contiguous characters) [code](code/string/remove-extra-spaces-or-other-chars.rb)

The code is tested against contiguous spaces but should work for other chars too.

```
ruby 2.5.0p0 (2017-12-25 revision 61468) [x86_64-linux]
Warming up --------------------------------------
String#gsub/regex+/ 1.644k i/100ms
String#squeeze 24.681k i/100ms
Calculating -------------------------------------
String#gsub/regex+/ 14.668k (± 5.1%) i/s - 73.980k in 5.056887s
String#squeeze 372.910k (± 8.4%) i/s - 1.851M in 5.011881s

Comparison:
String#squeeze: 372910.3 i/s
String#gsub/regex+/: 14668.1 i/s - 25.42x slower
```


### Range

Expand Down
24 changes: 24 additions & 0 deletions code/string/remove-extra-spaces-or-other-chars.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
require 'benchmark/ips'

PASSAGE = <<~LIPSUM
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
LIPSUM

raise unless PASSAGE.gsub(/ +/, " ") == PASSAGE.squeeze(" ")

def slow
PASSAGE.gsub(/ +/, " ")
end

def fast
PASSAGE.squeeze(" ")
end

Benchmark.ips do |x|
x.report('String#gsub/regex+/') { slow }
x.report('String#squeeze') { fast }
x.compare!
end