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

切片字符串"Hello world!"[0, 5] == 'Hello' 0,5 "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? 应该是我们的第一选择。 如果我们需要使用模式,那么切片或使用正则表达式是显而易见的选择。