字符串切片的算法复杂度是多少? (实用,真实世界)

时间:2017-12-09 21:59:43

标签: javascript big-o v8

在现代,v8 Javascript中,String.prototype.slice的算法复杂度是多少?

要清楚,我正在寻找现实世界,实用的数字或经验法则。

快速测试

我试图通过在最近的Chrome中运行两个快速测试来粗略估计。测试1将一串长度为Name Traceback (most recent call last): File "C:\Python\Data mon\csv_to_list.py", line 6, in <module> print(line[0]) IndexError: list index out of range 的字符串切成两半。测试2切割字符串中每个索引的长度为N的字符串(所以N次)。令人困惑的是,两者都在N时间运行。发生了什么事?

测试1

O(N)

测试2

let input = '';
let string = ' '.repeat(20000000);
for (let i = 0; i < 50; i++) {
    input += string;
    console.time(i);
    const y = input.slice(i / 2);
    console.timeEnd(i);
}

Chrome版本:Chrome版本63.0.3239.84(官方版本)(64位)

1 个答案:

答案 0 :(得分:3)

是的,V8有optimised string slicing to O(1)。这当然很大程度上取决于所有字符串发生了什么,他们可能需要稍后复制。

以上链接的相关实施是:

Sliced String diagram

{"id":"test",
"name":"test movie",
"description":"test movie",
"stars":"test movie",
"length":"test movie",
"image":"test movie",
"year":"test movie",
"rating":"test movie",
"director":"test movie",
"url":"test movie"
}

还要注意您的快速测试结果。由于您对// The Sliced String class describes strings that are substrings of another // sequential string. The motivation is to save time and memory when creating // a substring. A Sliced String is described as a pointer to the parent, // the offset from the start of the parent string and the length. Using // a Sliced String therefore requires unpacking of the parent string and // adding the offset to the start address. A substring of a Sliced String // are not nested since the double indirection is simplified when creating // such a substring. // Currently missing features are: // - handling externalized parent strings // - external strings as parent // - truncating sliced string to enable otherwise unneeded parent to be GC'ed. class SlicedString: public String { // ... }; 变量一无所知,切片甚至整个循环可能会被优化器作为死代码消除。如果您正在进行基准测试,请在实际的现实世界数据上进行测试。