Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

String#=~ faster than String#match #59

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,29 @@ Comparison:
String#=~: 854830.3 i/s - 3.32x slower
```

##### `String#match` vs `String#=~` [code ](code/string/match-vs-=~.rb)

> :warning: <br>
> Sometimes you cant replace `match` with `=~`, <br />
> This is only useful for cases where you are checkin <br />
> 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)

```
Expand Down
15 changes: 15 additions & 0 deletions code/string/match-vs-=~.rb
Original file line number Diff line number Diff line change
@@ -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