3
切分字符串"Hello world!"[0, 5] == 'Hello'
是Ruby中常用的一種習慣用法,用於比較字符串的第一個或最後n個字符與另一個字符串。正則表達式也可以做到這一點。然後有和end_with?
這也可以做到這一點。使用Ruby比較字符串的開始或結束與子字符串的最快方法是什麼?
我應該使用哪種速度?
切分字符串"Hello world!"[0, 5] == 'Hello'
是Ruby中常用的一種習慣用法,用於比較字符串的第一個或最後n個字符與另一個字符串。正則表達式也可以做到這一點。然後有和end_with?
這也可以做到這一點。使用Ruby比較字符串的開始或結束與子字符串的最快方法是什麼?
我應該使用哪種速度?
考慮這些測試:
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?
應該是我們的第一選擇。如果我們需要使用模式,那麼切片或使用正則表達式是明顯的選擇。
基準測試有意義。期待start_with?和end_with?更快,因爲它們可能不會構建任何字符串並將其返回給您,並可以對字符串本身進行比較。 – Mircea
'start_with?'和'end_with?'的速度很快的原因是因爲它們已經被編譯並正在使用'memcmp()',而沒有被解釋,並且不依賴調用正則表達式引擎。換句話說,他們依靠C函數來比較字符/字節,這些字符/字節快速變暗。 –
我相信我們同意:)(即說同樣的事情) – Mircea