最佳字符串匹配算法及其在Ruby中的实现?

最佳字符串匹配算法及其在Ruby中的实现?,ruby,performance,algorithm,string-matching,Ruby,Performance,Algorithm,String Matching,我有两个字符串string1和string2。检查string1中是否存在string2的最佳选项是什么。如何在Ruby中实现。目前我正在使用Regexmatch 试试看 string1.include? string2 这应该可以完成任务 1.9.3p194 :016 > Benchmark.measure{ 1_000_000.times{ 'asd'['a'] } } => 0.430000 0.000000 0.430000 ( 0.431638) 1.9

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

试试看

string1.include? string2
这应该可以完成任务

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)