2015-10-06 42 views

回答

4

考虑这些测试:

require 'fruity' 

STR = '!' + ('a'..'z').to_a.join # => "!abcdefghijklmnopqrstuvwxyz" 

结果的单个字符开始的字符串:

compare do 
    _slice { STR[0] == '!' } 
    _start_with { STR.start_with?('!') } 
    _regex { !!STR[/^!/] } 
end 

# >> Running each test 32768 times. Test will take about 1 second. 
# >> _start_with is faster than _slice by 2x ± 1.0 
# >> _slice is similar to _regex 

结果开始的字符串的多个字符:

compare do 
    _slice { STR[0..4] == '!abcd' } 
    _start_with { STR.start_with?('!abcd') } 
    _regex { !!STR[/^!abcd/] } 
end 

# >> Running each test 32768 times. Test will take about 2 seconds. 
# >> _start_with is faster than _slice by 2x ± 1.0 
# >> _slice is similar to _regex 

结果为单个字符结尾的字符:

compare do 
    _slice { STR[-1] == 'z' } 
    _end_with { STR.end_with?('z') } 
    _regex { !!STR[/z$/] } 
end 

# >> Running each test 32768 times. Test will take about 2 seconds. 
# >> _end_with is faster than _slice by 2x ± 1.0 
# >> _slice is faster than _regex by 2x ± 1.0 

结果结尾的字符串的多个字符:

compare do 
    _slice { STR[-5..-1] == 'vwxyz' } 
    _end_with { STR.end_with?('vwxyz') } 
    _regex { !!STR[/vwxyz$/] } 
end 

# >> Running each test 16384 times. Test will take about 1 second. 
# >> _end_with is faster than _slice by 2x ± 1.0 
# >> _slice is similar to _regex 

所以,清晰度和速度和end_with?应该是我们的第一选择。如果我们需要使用模式,那么切片或使用正则表达式是明显的选择。

+0

基准测试有意义。期待start_with?和end_with?更快,因为它们可能不会构建任何字符串并将其返回给您,并可以对字符串本身进行比较。 – Mircea

+0

'start_with?'和'end_with?'的速度很快的原因是因为它们已经被编译并正在使用'memcmp()',而没有被解释,并且不依赖调用正则表达式引擎。换句话说,他们依靠C函数来比较字符/字节,这些字符/字节快速变暗。 –

+0

我相信我们同意:)(即说同样的事情) – Mircea

相关问题