LoginSignup
23
23

More than 5 years have passed since last update.

「正規表現:悪い表現、いい表現、最良の表現」のRubyベンチマーク

Posted at

POSTDに「正規表現:悪い表現、いい表現、最良の表現」という記事が上がっていたので、興味本位でRubyでベンチマークとってみた。

スペック

  Model Name: Mac mini
  Model Identifier: Macmini5,1
  Processor Name: Intel Core i5
  Processor Speed: 2.3 GHz
  Number of Processors: 1
  Total Number of Cores: 2
  L2 Cache (per Core): 256 KB
  L3 Cache: 3 MB
  Memory: 8 GB
$ ruby -v
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin13]

コード

regexp.rb
#!/usr/bin/env ruby

require 'benchmark'

t = '2014-08-26 app[web.1]: 50.0.134.125 - - [26/Aug/2014 00:27:41] "GET / HTTP/1.1" 200 14 0.0005'

rp1 = Regexp.new('.* (.*)\[(.*)\]:.*') # 悪い正規表現
rp2 = Regexp.new('[12]\d{3}-[01]\d-[0-3]\d (.*)\[(.*)\]:.*') # いい正規表現
rp3 = Regexp.new('[12]\d{3}-[01]\d-[0-3]\d ([^ \[]*?)\[([^\]]*?)\]:.*') # 最良の正規表現

n = 1000000
Benchmark.bm 6 do |x|
  x.report('bad:') { n.times do rp1 =~ t end }
  x.report('better:') { n.times do rp2 =~ t end }
  x.report('best:') { n.times do rp3 =~ t end }
end

結果

             user     system      total        real
bad:    14.310000   0.020000  14.330000 ( 14.342206)
better:  4.590000   0.000000   4.590000 (  4.597231)
best:    1.890000   0.000000   1.890000 (  1.894905)

と、案の定最良の正規表現が一番速いという結果になった

結論

最良の正規表現を書こう

23
23
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
23