Skip to content

Instantly share code, notes, and snippets.

@bcardiff
Last active March 17, 2016 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcardiff/f3930c4797f52905977a to your computer and use it in GitHub Desktop.
Save bcardiff/f3930c4797f52905977a to your computer and use it in GitHub Desktop.
benchmark for headers matching
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
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