Skip to content

Commit 076b96b

Browse files
committed
String#=~ faster than String#match
If you're only looking for presence of a match and don't need the matchdata, use String#=~ schneems/rails@1bf50ba#commitcomment-12572839
1 parent 9e2b29c commit 076b96b

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -682,6 +682,29 @@ Comparison:
682682
String#=~: 854830.3 i/s - 3.32x slower
683683
```
684684

685+
##### `String#match` vs `String#=~` [code ](code/string/match-vs-=~.rb)
686+
687+
> :warning: <br>
688+
> Sometimes you cant replace `match` with `=~`, <br />
689+
> This is only useful for cases where you are checkin <br />
690+
> for a match and not using the resultant match object.
691+
692+
```
693+
$ ruby -v code/string/match-vs-=~.rb
694+
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin14]
695+
Calculating -------------------------------------
696+
String#=~ 69.889k i/100ms
697+
String#match 66.715k i/100ms
698+
-------------------------------------------------
699+
String#=~ 1.854M (±12.2%) i/s - 9.155M
700+
String#match 1.594M (±11.0%) i/s - 7.939M
701+
702+
Comparison:
703+
String#=~: 1853861.7 i/s
704+
String#match: 1593971.6 i/s - 1.16x slower
705+
```
706+
707+
685708
##### `String#gsub` vs `String#sub` [code](code/string/gsub-vs-sub.rb)
686709

687710
```

code/string/match-vs-=~.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
require 'benchmark/ips'
2+
3+
def fast
4+
"foo".freeze =~ /boo/
5+
end
6+
7+
def slow
8+
"foo".freeze.match(/boo/)
9+
end
10+
11+
Benchmark.ips do |x|
12+
x.report("String#=~") { fast }
13+
x.report("String#match") { slow }
14+
x.compare!
15+
end

0 commit comments

Comments
 (0)