Skip to content

Instantly share code, notes, and snippets.

@gavinlaking
Last active December 25, 2015 08:49
Show Gist options
  • Save gavinlaking/6949417 to your computer and use it in GitHub Desktop.
Save gavinlaking/6949417 to your computer and use it in GitHub Desktop.
Benchmarking the #matches method from Gary Bernhardt's 'selecta' (https://github.com/garybernhardt/selecta). Here I offer an 'unfair' (in that I'm asking the method to check through ~235,000 choices) run, but it highlights to me that this method is not as slow as I first thought.
$ ruby tmp.rb
Rehearsal -------------------------------------------------
file read 0.000000 0.000000 0.000000 ( 0.003113)
file to array 0.040000 0.010000 0.050000 ( 0.039986)
#matches 0.230000 0.000000 0.230000 ( 0.230347)
---------------------------------------- total: 0.280000sec
user system total real
file read 0.000000 0.000000 0.000000 ( 0.001798)
file to array 0.040000 0.000000 0.040000 ( 0.040375)
#matches 0.240000 0.000000 0.240000 ( 0.240455)
matches: 2181
choices: 235886
-- ruby tmp.rb --------------------------------------------------------
require "benchmark"
search_string = "term"
choices = File.read("/usr/share/dict/words").split("\n")
def matches(search_string, choices)
re = search_string.split(//).map(&Regexp.method(:escape)).join('.*')
re = /#{re}/i
choices.select { |s| s =~ re }.sort_by(&:length)
end
Benchmark.bmbm do |bm|
bm.report("file read") do
File.read("/usr/share/dict/words")
end
bm.report("file to array") do
File.read("/usr/share/dict/words").split("\n")
end
bm.report("#matches") do
matches(search_string, choices)
end
end
puts "matches: #{matches(search_string, choices).size}"
puts "choices: #{choices.size}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment