1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# Benchmarking answers to http://stackoverflow.com/questions/9333952/in-ruby-how-to-make-the-string-include-method-ignore-case/9334066

# http://www.gutenberg.org/cache/epub/1661/pg1661.txt
strings = IO.read('sherlock.txt').scan(/\w+/) # 109,222 words

known = 500.times.map do
  strings.sample.downcase.chars.map{ |c| rand<0.5 ? c.upcase : c }.join
end
words = known.flat_map{ |s| [s, s+"-"] } # \w does not include -

require 'benchmark'
Benchmark.bm(10) do |x|
  x.report('regex'){
    words.each do |w|
      re = /\A#{w}\z/i
      strings.any?{ |s| s=~re }
    end
  }
  x.report('casecmp'){
    words.each do |w|
      strings.any?{ |s| s.casecmp(w)==0 }
    end
  }
  x.report('downarray'){
    words.each do |w|
      strings.map(&:downcase).include?(w.downcase)
    end
  }
  x.report('downonce'){
    downed = strings.map(&:downcase)
    words.each do |w|
      downed.include?(w.downcase)
    end
  }
end


#=>                 user     system      total        real
#=> regex      26.770000   0.000000  26.770000 ( 26.760000)
#=> casecmp     9.375000   0.000000   9.375000 (  9.377000)
#=> downarray  29.329000   0.000000  29.329000 ( 29.332000)
#=> downonce    3.619000   0.000000   3.619000 (  3.620000)