rubyでdowncase VS 正規表現
ついでにupcaseも。
大文字と小文字を区別せずに大量のデータを比較する場合、downcaseが速いのか正規表現の方が速いのか、確認してみました。コードは以下です。(こんなんでいいかな・・・?)
require 'benchmark' a = "BaNaNa RiNgo BuDo IchiGO" b = "banana RINGO budo ICHIGO" n = ARGV[0].to_i puts Benchmark::CAPTION puts Benchmark.measure{ n.times { a.downcase == b.downcase } } puts Benchmark.measure{ n.times { a.upcase == b.upcase } } puts Benchmark.measure{ n.times { a =~ /^#{b}$/i } }
実行結果は以下です。1000回、10000回、100000回で実行しました。
$ ruby test.rb 1000 user system total real 0.000000 0.000000 0.000000 ( 0.000889) 0.000000 0.000000 0.000000 ( 0.000854) 0.000000 0.000000 0.000000 ( 0.004305) $ ruby test.rb 10000 user system total real 0.010000 0.000000 0.010000 ( 0.011290) 0.010000 0.000000 0.010000 ( 0.010139) 0.040000 0.000000 0.040000 ( 0.040895) $ ruby test.rb 100000 user system total real 0.100000 0.000000 0.100000 ( 0.095221) 0.090000 0.000000 0.090000 ( 0.094485) 0.370000 0.010000 0.380000 ( 0.382025)
断然downcase(upcase)の方が速かったです。
世の中の常識ですかね?
今まで調子に乗って正規表現でやってました。
反省します!