Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'benchmark/ips'
TEST_STRING = "FooBar" * 10
Benchmark.ips do |x|
x.report("count") do
TEST_STRING.count('[A-Z]')
end
x.report("gsub") do
TEST_STRING.gsub(/[^A-Z]/, "").length
end
x.report("scan") do
TEST_STRING.scan(/[A-Z]/).size
end
x.compare!
end
@bradland

This comment has been minimized.

Copy link
Owner Author

@bradland bradland commented Mar 9, 2015

Results (iMac 3.5 GHz i7):

$ ruby scan-v-gsub.rb 
Calculating -------------------------------------
                gsub    11.336k i/100ms
                scan    15.729k i/100ms
               count    79.687k i/100ms
-------------------------------------------------
                gsub    122.512k (± 1.7%) i/s -    623.480k
                scan    174.512k (± 1.7%) i/s -    880.824k
               count      1.527M (± 1.9%) i/s -      7.650M

Comparison:
               count:  1526699.9 i/s
                scan:   174512.1 i/s - 8.75x slower
                gsub:   122512.1 i/s - 12.46x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment