Ruby中最好的字符串匹配算法和实现?

Bhu*_*dha 2 ruby algorithm performance string-matching

我有这两个字符串string1string2.什么是检查,如果我最好的选择string2是目前在string1.我如何在Ruby中实现.目前我正在使用Regex比赛.

mde*_*tis 7

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)
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,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)
Run Code Online (Sandbox Code Playgroud)

但:

# 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)
Run Code Online (Sandbox Code Playgroud)

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