Last active
August 29, 2015 14:21
-
-
Save Bodacious/d1fd3ea02a6304f72b5f to your computer and use it in GitHub Desktop.
Ruby Benchmark: What's the fastest way to check the start of a String in Ruby?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'benchmark' | |
| TIMES = 1000000 | |
| STRING = "this is a long and bad-ass string" | |
| Benchmark.bmbm do |test| | |
| test.report("Index") do | |
| TIMES.times { STRING.index("this is") } | |
| end | |
| test.report("start_with?") do | |
| TIMES.times { STRING.start_with?("this is") } | |
| end | |
| test.report("=~ (^)") do | |
| TIMES.times { STRING =~ /^this is/ } | |
| end | |
| test.report("=~ (\A)") do | |
| TIMES.times { STRING =~ /^this is/ } | |
| end | |
| test.report("scan (^)") do | |
| TIMES.times { STRING.scan /^this is/ } | |
| end | |
| test.report("scan (\A)") do | |
| TIMES.times { STRING.scan /^this is/ } | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Rehearsal ------------------------------------------------ | |
| Index 0.260000 0.000000 0.260000 ( 0.264949) | |
| start_with? 0.190000 0.010000 0.200000 ( 0.193379) | |
| =~ (^) 0.270000 0.000000 0.270000 ( 0.272468) | |
| =~ (A) 0.250000 0.000000 0.250000 ( 0.258506) | |
| scan (^) 1.740000 0.020000 1.760000 ( 1.776399) | |
| scan (A) 1.750000 0.010000 1.760000 ( 1.776322) | |
| --------------------------------------- total: 4.500000sec | |
| user system total real | |
| Index 0.280000 0.000000 0.280000 ( 0.283709) | |
| start_with? 0.200000 0.000000 0.200000 ( 0.200284) | |
| =~ (^) 0.280000 0.000000 0.280000 ( 0.282534) | |
| =~ (A) 0.300000 0.000000 0.300000 ( 0.291691) | |
| scan (^) 1.710000 0.010000 1.720000 ( 1.728397) | |
| scan (A) 1.700000 0.020000 1.720000 ( 1.713138) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment