rubyで正規表現を使って文字列を判定するときのコツ
処理速度が求められる箇所で正規表現を使う場合"oフラグ"を使うと
正規表現オブジェクトが再生成されずに有効だと聞いたことがあったので
Regexpを使ったケースと比較検証してみた。(ruby標準のprofilerを利用)
require 'profiler' def profile Profiler__.start_profile 100000.times do |i| yield end Profiler__.print_profile(STDOUT) end puts "固定パターン" profile do "hoge.gif" =~ /.gif/ end puts "変数使用+oフラグ" pattern = ".gif" profile do "hoge.gif" =~ /#{pattern}/o end puts "Regexpを使用" regexp = Regexp.new("#{pattern}") profile do regexp.match("hoge.gif") end
結果はこんな感じ
固定パターン % cumulative self self total time seconds seconds calls ms/call ms/call name 100.00 20.60 20.60 1 20599.00 20599.00 Integer#times 0.00 20.60 0.00 1 0.00 20599.00 #toplevel 変数使用+oフラグ % cumulative self self total time seconds seconds calls ms/call ms/call name 100.00 22.39 22.39 1 22392.00 22392.00 Integer#times 0.00 22.39 0.00 1 0.00 22392.00 #toplevel Regexpを使用 % cumulative self self total time seconds seconds calls ms/call ms/call name 76.95 50.54 50.54 1 50539.00 65675.00 Integer#times 23.05 65.67 15.14 100000 0.15 0.15 Regexp#match 0.00 65.67 0.00 1 0.00 65675.00 #toplevel
正規表現を使わない固定パターンが速いのは当たり前だとして、
Regexpを使ったほうが遅いのが意外だった。
rubyバージョンは1.8.6