切换字符串"Hello world!"[0, 5] == 'Hello'
是Ruby中常用的习惯用法,用于将字符串的前n个或后n个字符与另一个字符串进行比较。正则表达式也可以这样做。然后还有start_with?
和end_with?
也可以这样做。
我应该以最快的速度使用哪个?
答案 0 :(得分: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
因此,为了清晰度和速度,start_with?
和end_with?
应该是我们的首选。如果我们需要使用模式,那么切片或使用正则表达式是明显的选择。