Skip to content

Instantly share code, notes, and snippets.

@bradland
Created March 9, 2015 01:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradland/5bfabe4fea408dd2cbd8 to your computer and use it in GitHub Desktop.
Save bradland/5bfabe4fea408dd2cbd8 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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