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

前端 未结 7 1463
独厮守ぢ
独厮守ぢ 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条回答
  • 2020-12-13 06:12

    This is a simple benchmark:

    require 'benchmark'
    
    "test123" =~ /1/
    => 4
    Benchmark.measure{ 1000000.times { "test123" =~ /1/ } }
    =>   0.610000   0.000000   0.610000 (  0.578133)
    
    "test123"[/1/]
    => "1"
    Benchmark.measure{ 1000000.times { "test123"[/1/] } }
    =>   0.718000   0.000000   0.718000 (  0.750010)
    
    irb(main):019:0> "test123".match(/1/)
    => #<MatchData "1">
    Benchmark.measure{ 1000000.times { "test123".match(/1/) } }
    =>   1.703000   0.000000   1.703000 (  1.578146)
    

    So =~ is faster but it depends what you want to have as a returned value. If you just want to check if the text contains a regex or not use =~

    0 讨论(0)
提交回复
热议问题