From d99f25157146465c8a80656caa0ccc7070221b28 Mon Sep 17 00:00:00 2001 From: Adrian Setyadi Date: Sun, 11 Feb 2018 20:33:00 +0700 Subject: [PATCH] Remove extra spaces (or other contiguous chars) --- README.md | 18 ++++++++++++++ .../remove-extra-spaces-or-other-chars.rb | 24 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 code/string/remove-extra-spaces-or-other-chars.rb diff --git a/README.md b/README.md index cfc91b9..8c36bf1 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/code/string/remove-extra-spaces-or-other-chars.rb b/code/string/remove-extra-spaces-or-other-chars.rb new file mode 100644 index 0000000..fb1349f --- /dev/null +++ b/code/string/remove-extra-spaces-or-other-chars.rb @@ -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