JS:创建从索引0开始的所有子字符串的最快方法

JS: Fastest way to create all substrings starting at index 0

本文关键字:字符串 方法 JS 创建 索引 开始      更新时间:2024-07-02

因此,我正在寻找一种方法,从索引0开始的较大字符串中生成所有可能的子字符串。假设我们有

var a = "test";

然后我想生成

"test", "tes", "te" and "t"

我想象用子串、子串或切片来做这件事,我在这里测试了它们:http://jsperf.com/loop-over-string

现在,slice方法的速度几乎是其他方法的两倍。有人能解释一下吗?或者有更快的方法可以做到这一点吗?

在基准测试中,slice更快,因为text的长度每次迭代都会减少。

如果您查看V8中的substrsubstringslice实现,您会发现它们使用相同的内部函数%_SubString。他们只是以微不足道的成本操纵其参数。

  • String.prototype.slice:https://github.com/v8/v8/blob/master/src/string.js#L567
  • String.prototype.substring:https://github.com/v8/v8/blob/master/src/string.js#L713
  • String.prototype.substr:https://github.com/v8/v8/blob/master/src/string.js#L748

这似乎更快:

substr = ""
for (var i = 0; i < length; i++) {
    substr += text.charAt(i)
}

http://jsperf.com/loop-over-string/3