Skip to content

Instantly share code, notes, and snippets.

@hyeomans
Last active December 16, 2015 22:48
Show Gist options
  • Save hyeomans/5509283 to your computer and use it in GitHub Desktop.
Save hyeomans/5509283 to your computer and use it in GitHub Desktop.
Benchmarking regex against kernel string comparison
Setup the Benchmark
[1] pry(main)> require 'benchmark'
=> true
[2] pry(main)> test_string = "/foo/bar/bah/bing"
=> "/foo/bar/bah/bing"
String#starts_with?
[3] pry(main)> Benchmark.realtime { (1..10000).to_a.each { %r{^/foo}.match(test_string) } }
=> 0.009987447
[4] pry(main)> Benchmark.realtime { (1..10000).to_a.each { test_string.start_with?("foo") } }
=> 0.003103276
String#end_with?
[5] pry(main)> Benchmark.realtime { (1..10000).to_a.each { %r{bing$}.match(test_string) } }
=> 0.015837275
[6] pry(main)> Benchmark.realtime { (1..10000).to_a.each { test_string.end_with?("bing") } }
=> 0.005633547
String#include?
[7] pry(main)> Benchmark.realtime { (1..10000).to_a.each { %r{^.*bar.*$}.match(test_string) } }
=> 0.025630178
[8] pry(main)> Benchmark.realtime { (1..10000).to_a.each { test_string.include?("bar") } }
=> 0.010360719
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment