gpt4 book ai didi

ruby - 使用 Ruby 将字符串的开头或结尾与子字符串进行比较的最快方法是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 07:55:24 27 4
gpt4 key购买 nike

字符串切片 "Hello world!"[0, 5] == 'Hello' 是 Ruby 中的一个常用习惯用法,用于将一个字符串的前 n 个或最后 n 个字符与另一个字符串进行比较。正则表达式也可以做到。然后还有 start_with?end_with? 也可以做到这一点。

我应该使用哪种速度最快?

最佳答案

考虑这些测试:

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? 应该是我们的首选。如果我们需要使用模式,那么切片或使用正则表达式是显而易见的选择。

关于ruby - 使用 Ruby 将字符串的开头或结尾与子字符串进行比较的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32976739/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com