Skip to content

Instantly share code, notes, and snippets.

@johnthepink
Last active November 28, 2018 18:58
Show Gist options
  • Save johnthepink/57f4c1bc457fed7862f2fecaa388ba40 to your computer and use it in GitHub Desktop.
Save johnthepink/57f4c1bc457fed7862f2fecaa388ba40 to your computer and use it in GitHub Desktop.
Ruby String Matching Benchmark
require 'benchmark'
require 'securerandom'
words = []
# generate list of random "words"
10_000.times.map do
words << SecureRandom.hex
end
# create string to compare them to.
# since it is a random hash based off time, it will never match
string = SecureRandom.hex
# compare words one at a time in the array to string
puts Benchmark.measure {
words.any? { |word| string.include?(word) }
}
# 0.000880
# compare with string using regex
puts Benchmark.measure {
regex = /#{words.join('|')}/
regex === string
}
# 0.033893
# compare with regex premade
regex = /#{words.join('|')}/
puts Benchmark.measure {
regex === string
}
# 0.001580
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment