【问题标题】:Ruby - Performance of regexRuby - 正则表达式的性能
【发布时间】:2011-07-14 00:40:26
【问题描述】:

我正在尝试查看是否有更好的方法来查找字符串中单词的完全匹配。 我正在我的数据库表中查找字段“标题”的单词。 记录的数量差异很大,我看到的性能非常可怕。

这是我对结果进行基准测试的 3 种方法。

title.split.include(search_string)
/\b#{search_string }\b/ =~ title
title.include?(search_string)

最佳性能是title.include?(search_string) 它不进行精确的单词搜索(我正在寻找精确的单词搜索)

  def do_benchmark(search_results, search_string)
    n=1000

    Benchmark.bm do |x|
      x.report("\b word search \b:")           {
        n.times {
          search_results.each {|search_result|
          title = search_result.title         
          /\b#{search_string}\b/ =~ title         
        }
      }
     }
  end

    Benchmark.bm do |x|
      search_string = search.search_string
      x.report("split.include? search:") {
        n.times {
          search_results.each {|search_result|
            title = search_result.title
            title.split.include?(search_string)
          }

        }
      }
    end

   Benchmark.bm do |x|
     search_string = search.search_string
     x.report("string include? search:") {
     n.times {
       search_results.each {|search_result|
       title = search_result.title
       title.include?(search_string)
     }

    }
  }
end

"processing: 6234 records"
"Looking for term: red ferrari"
 user     system      total        real
 word search: 50.380000   2.600000  52.980000 ( 57.019927)
 user     system      total        real
 split.include? search: 54.600000   0.260000  54.860000 ( 57.854837)
 user     system      total        real
 string include? search: 21.600000   0.060000  21.660000 ( 21.949715)

有什么方法可以获得更好的性能和精确的字符串匹配结果?

【问题讨论】:

    标签: ruby regex performance search full-text-search


    【解决方案1】:

    对字符串中的空格进行拆分,检查拆分字符串中的每个单词,然后检查== 运算符。

    【讨论】:

    • 这基本上就是'hello world'.split.include? 'foo' 所做的。
    【解决方案2】:

    您想要对模型字段进行全文搜索。这最好不要通过正则表达式扫描,而是通过专门的全文检索索引来完成。我建议您使用以下方法之一,而不是自己动手:

    • acts_as_indexed
    • 狮身人面像
    • 雪貂
    • 夏片
    • Lucene/Solr

    这里有一些链接,其中包含有关选项的更多详细信息:

    【讨论】:

    • 感谢马克的指点。我正在做一个快速而肮脏的黑客攻击,但显然在压力下并不能很好地承受。我会查看您发布的链接。
    猜你喜欢
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多