Last active
March 17, 2016 15:31
-
-
Save bcardiff/f3930c4797f52905977a to your computer and use it in GitHub Desktop.
benchmark for headers matching
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" | |
def string_contains_word(source, word) | |
return false unless source | |
start = source.index(word) | |
return false unless start | |
return false if start > 0 && source[start-1].alphanumeric? | |
return false if start + word.size < source.size && source[start + word.size].alphanumeric? | |
true | |
end | |
# string_contains_word("lorem", "em") | |
# string_contains_word("lorem", "lorem") | |
# string_contains_word("foo, lorem, fdf", "lorem") | |
# string_contains_word("foo, lorem , fdf", "lorem") | |
# string_contains_word("xloremx", "lorem") | |
# string_contains_word("lorem", "nono") | |
# string_contains_word("", "nono") | |
# string_contains_word(nil, "nono") | |
Benchmark.ips do |x| | |
x.report("includes") { | |
"keep-alive, Upgrade".includes? "Upgrade" # this is a buggy implementation | |
} | |
x.report("string_contains_word") { | |
string_contains_word "keep-alive, Upgrade", "Upgrade" | |
} | |
x.report("split strip") { | |
"keep-alive, Upgrade".split(',').any? { |s| s.strip == "Upgrade" } | |
} | |
x.report("match") { | |
"keep-alive, Upgrade" =~ /\bUpgrade\b/ | |
} | |
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
crystal match.cr --release | |
includes 10.21M (± 4.02%) fastest | |
string_contains_word 9.77M (± 5.61%) 1.05× slower | |
split strip 2.17M (± 1.51%) 4.71× slower | |
match 3M (± 1.72%) 3.41× slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment