给定一个字符串,返回字符串中换行符开头的字符位置数组的最有效方法是什么?
text =<<_
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
_
预期的:
find_newlines(text) # => [0, 80, 155, 233, 313, 393]
我发布我自己的答案。我想接受最快的方式作为接受的答案。
添加新答案时,此处的基准测试结果将更新
require "fruity"
compare do
padde1 {find_newlines_padde1(text)}
digitalross1 {find_newlines_digitalross1(text)}
sawa1 {find_newlines1(text)}
sawa2 {find_newlines2(text)}
end
# Running each test 512 times. Test will take about 1 second.
# digitalross1 is faster than sawa2 by 5x ± 0.1
# sawa2 is faster than sawa1 by 21.999999999999996% ± 1.0%
# sawa1 is faster than padde1 by 4.0000000000000036% ± 1.0%