【问题标题】:Best String matching algorithm and implementation in Ruby?Ruby中最好的字符串匹配算法和实现?
【发布时间】:2012-07-30 06:52:42
【问题描述】:

我有这两个字符串string1string2。检查string2 是否存在于string1 中的最佳选择是什么。我如何在 Ruby 中实现。目前我正在使用Regex 匹配。

【问题讨论】:

    标签: ruby performance algorithm string-matching


    【解决方案1】:
    1.9.3p194 :016 > Benchmark.measure{ 1_000_000.times{ 'asd'['a'] } }
     =>   0.430000   0.000000   0.430000 (  0.431638)
    
    1.9.3p194 :017 > Benchmark.measure{ 1_000_000.times{ 'asd' =~ /a/ } }
     =>   0.420000   0.000000   0.420000 (  0.415391)
    
    1.9.3p194 :018 > Benchmark.measure{ 1_000_000.times{ 'asd'.include? 'a' } }
     =>   0.340000   0.000000   0.340000 (  0.343843)
    

    令人惊讶的是,count('a') > 0 给了我很好的结果:

    1.9.3p194 :031 >   Benchmark.measure{ 10_000_000.times{ 'asd'.count('a') > 0 } }
     =>   3.100000   0.000000   3.100000 (  3.099447)
    
    1.9.3p194 :032 > Benchmark.measure{ 10_000_000.times{ 'asd'.include?('a') } }
     =>   3.220000   0.000000   3.220000 (  3.226521)
    

    但是:

    # count('a') > 0
    1.9.3p194 :056 >   Benchmark.measure{ 10_000_000.times{ 'asdrsguoing93hafehbsefu3nr3wrbibaefiafb3uwfniw4ufnsbei'.count('a') > 0 } }
     =>   3.630000   0.000000   3.630000 (  3.633329)
    # include?('a')
    1.9.3p194 :057 > Benchmark.measure{ 10_000_000.times{ 'asdrsguoing93hafehbsefu3nr3wrbibaefiafb3uwfniw4ufnsbei'.include?('a') } }
     =>   3.220000   0.000000   3.220000 (  3.224986)
    # =~ /a/
    1.9.3p194 :058 > Benchmark.measure{ 10_000_000.times{ 'asdrsguoing93hafehbsefu3nr3wrbibaefiafb3uwfniw4ufnsbei' =~ /a/ } }
     =>   3.040000   0.000000   3.040000 (  3.043130)
    

    所以:严格谈论性能,您应该考虑字符串的分布(很少是随机的)进行测试。说到表现力,也许include?是最好的选择。

    【讨论】:

      【解决方案2】:

      试试

      string1.include? string2
      

      这应该做的工作

      【讨论】:

      • 但这是最好的办法吗?
      • 您所说的“最佳”是什么意思?最少的代码,最快的,最少的内存消耗,最可靠/最强大的......
      猜你喜欢
      • 2012-12-12
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 2016-03-31
      • 2012-02-23
      • 2016-10-16
      • 2013-06-17
      相关资源
      最近更新 更多