Reputation: 6862
I have this two string string1
and string2
. What are my best option to check if string2
is present in string1
. How do I implement in Ruby. Currently I am using Regex
match.
Upvotes: 2
Views: 1344
Reputation: 8507
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)
Surprisingly, count('a') > 0
is giving me good results:
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)
But:
# 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)
So: talking strictly about performance, you should do a test considering the distribution of your strings (which rarely is random). Talking about expressivity, maybe include?
is the best choice.
Upvotes: 7