Last active
August 29, 2015 14:14
-
-
Save lcowell/4200e1f3fa6667512b5b to your computer and use it in GitHub Desktop.
regex_bench.rb
This file contains 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/ips' | |
str = "this.is.a.top.level.domain/foo/bar" | |
by_char = lambda {|s| | |
s.each_char.inject("") {|acc,c| | |
if c == "/" | |
break acc | |
end | |
acc << c | |
} | |
} | |
array = lambda {|s| | |
s.split("").take_while {|c| c != "/" }.join("") | |
} | |
index = lambda {|s| | |
s[0,s.index("/")] | |
} | |
r = %r{^[^\/]*} | |
regex = lambda {|s| | |
r.match(s)[0] | |
} | |
puts index.call(str) | |
puts regex.call(str) | |
puts array.call(str) | |
puts by_char.call(str) | |
Benchmark.ips do |x| | |
x.report("index") { index.call(str) } | |
x.report("regex") { regex.call(str) } | |
x.report("array") { array.call(str) } | |
x.report("regex") { by_char.call(str) } | |
end |
This file contains 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
this.is.a.top.level.domain | |
this.is.a.top.level.domain | |
this.is.a.top.level.domain | |
this.is.a.top.level.domain | |
Calculating ------------------------------------- | |
index 75109 i/100ms | |
regex 38009 i/100ms | |
array 4475 i/100ms | |
regex 9586 i/100ms | |
------------------------------------------------- | |
index 1387266.0 (±6.9%) i/s - 6910028 in 5.005856s | |
regex 500365.5 (±6.3%) i/s - 2508594 in 5.033506s | |
array 43816.5 (±7.2%) i/s - 219275 in 5.032708s | |
regex 96205.1 (±5.4%) i/s - 488886 in 5.096688s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment