diff --git a/README.md b/README.md index 391de20..6230bec 100644 --- a/README.md +++ b/README.md @@ -682,6 +682,29 @@ Comparison: String#=~: 854830.3 i/s - 3.32x slower ``` +##### `String#match` vs `String#=~` [code ](code/string/match-vs-=~.rb) + +> :warning:
+> Sometimes you cant replace `match` with `=~`,
+> This is only useful for cases where you are checkin
+> for a match and not using the resultant match object. + +``` +$ ruby -v code/string/match-vs-=~.rb +ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin14] +Calculating ------------------------------------- + String#=~ 69.889k i/100ms + String#match 66.715k i/100ms +------------------------------------------------- + String#=~ 1.854M (±12.2%) i/s - 9.155M + String#match 1.594M (±11.0%) i/s - 7.939M + +Comparison: + String#=~: 1853861.7 i/s + String#match: 1593971.6 i/s - 1.16x slower +``` + + ##### `String#gsub` vs `String#sub` [code](code/string/gsub-vs-sub.rb) ``` diff --git a/code/string/match-vs-=~.rb b/code/string/match-vs-=~.rb new file mode 100644 index 0000000..8b6dae6 --- /dev/null +++ b/code/string/match-vs-=~.rb @@ -0,0 +1,15 @@ +require 'benchmark/ips' + +def fast + "foo".freeze =~ /boo/ +end + +def slow + "foo".freeze.match(/boo/) +end + +Benchmark.ips do |x| + x.report("String#=~") { fast } + x.report("String#match") { slow } + x.compare! +end