Fastest way to check if a string matches a regexp in ruby?

前端 未结 7 1487
独厮守ぢ
独厮守ぢ 2020-12-13 05:07

What is the fastest way to check if a string matches a regular expression in Ruby?

My problem is that I have to \"egrep\" through a huge list of strings to find whic

7条回答
  •  -上瘾入骨i
    2020-12-13 06:08

    To complete Wiktor Stribiżew and Dougui answers I would say that /regex/.match?("string") about as fast as "string".match?(/regex/).

    Ruby 2.4.0 (10 000 000 ~2 sec)

    2.4.0 > require 'benchmark'
     => true 
    2.4.0 > Benchmark.measure{ 10000000.times { /^CVE-[0-9]{4}-[0-9]{4,}$/.match?("CVE-2018-1589") } }
     => # 
    2.4.0 > Benchmark.measure{ 10000000.times { "CVE-2018-1589".match?(/^CVE-[0-9]{4}-[0-9]{4,}$/) } }
     => # 
    

    Ruby 2.6.2 (100 000 000 ~20 sec)

    irb(main):001:0> require 'benchmark'
    => true
    irb(main):005:0> Benchmark.measure{ 100000000.times { /^CVE-[0-9]{4}-[0-9]{4,}$/.match?("CVE-2018-1589") } }
    => #
    irb(main):004:0> Benchmark.measure{ 100000000.times { "CVE-2018-1589".match?(/^CVE-[0-9]{4}-[0-9]{4,}$/) } }
    => #
    

    Note: times varies, sometimes /regex/.match?("string") is faster and sometimes "string".match?(/regex/), the differences maybe only due to the machine activity.

提交回复
热议问题