Last active
November 28, 2018 18:58
-
-
Save johnthepink/57f4c1bc457fed7862f2fecaa388ba40 to your computer and use it in GitHub Desktop.
Ruby String Matching Benchmark
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' | |
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