Skip to content

Instantly share code, notes, and snippets.

@284km
Created January 26, 2018 03:04
Show Gist options
  • Save 284km/706b5d4c1c9531bc0cc0f02e797d1079 to your computer and use it in GitHub Desktop.
Save 284km/706b5d4c1c9531bc0cc0f02e797d1079 to your computer and use it in GitHub Desktop.
String#match vs String#match?
require 'benchmark/ips'
# Because the methods avoid creating a `MatchData` object or saving backref.
# So, when `MatchData` is not used, use `match?` instead of `match`.
def fast
"aaacolorzzz".match?(/color/)
end
def slow
"aaacolorzzz".match(/color/)
end
def slow2
"aaacolorzzz" =~ /color/
end
Benchmark.ips do |x|
x.report('match?') { fast }
x.report('match') { slow }
x.report('=~') { slow2 }
x.compare!
end
__END__
$ ruby string_match-vs-string_match_question.rb
Warming up --------------------------------------
match? 184.230k i/100ms
match 66.680k i/100ms
=~ 71.225k i/100ms
Calculating -------------------------------------
match? 3.794M (±12.9%) i/s - 18.607M in 5.002392s
match 841.440k (±10.5%) i/s - 4.201M in 5.065411s
=~ 849.979k (±13.6%) i/s - 4.202M in 5.053991s
Comparison:
match?: 3794456.2 i/s
=~: 849978.8 i/s - 4.46x slower
match: 841440.3 i/s - 4.51x slower
ruby string_match-vs-string_match_question.rb 20.71s user 0.14s system 97% cpu 21.445 total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment