Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Regex benchmarks
require 'benchmark'
nelements = 10
nlines = 10
def repeating_string(base, elements, lines)
(([base]*elements).join(',')+"\n")*lines
end
# test string
s1 = repeating_string('xxxxxxxx',nelements,nlines)
s2 = repeating_string('xxxxxxxx',2*nelements,nlines)
# unrestricted globs
regex1 = repeating_string('.*',nelements,nlines)
r1 = Regexp.new(regex1)
# restricted globs
regex2 = repeating_string('[^,]*',nelements,nlines)
r2 = Regexp.new(regex2)
# unrestricted globs x2
regex3 = repeating_string('.*',2*nelements,nlines)
r3 = Regexp.new(regex3)
# restricted globs x2
regex4 = repeating_string('[^,]*',2*nelements,nlines)
r4 = Regexp.new(regex4)
n = 1000
Benchmark.bm(15) do |bench|
bench.report("regex1:") { n.times { s1 =~ r1 } }
bench.report("regex2:") { n.times { s1 =~ r2 } }
bench.report("regex3 (/100):") { (n/100).times { s2 =~ r3 } }
bench.report("regex4:") { n.times { s2 =~ r4 } }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment