【发布时间】:2017-10-07 11:53:03
【问题描述】:
我需要在 ES6 中将字符串转换为 TypedArrays(然后再转换回字符串)。 目前,这是通过以下功能完成的:
function string2array(s) {
return Uint32Array.from(s, (c) => c.codePointAt(0));
}
function array2string(a) {
return String.fromCodePoint(...a);
}
string2array 比array2string 慢两倍。我希望这两个功能同样快。我对它们如何工作的概念如下:
string2array(s):
allocate memory for array of length=s.length
foreach character (or surrogate pair):
get codePoint
push to array
return array
array2string(a):
allocate memory for string of lenght=a.length
foreach item in array
get String.fromCodePoint
push to string
return string
所以他们看起来和我相当。
- 为什么 string2array 比较慢?
- string2array 有更快的方法吗?
这是我的测试用例:
function testConversions() {
"use strict";
const data = "????ABCDEFGHIJKLM????NOPQRSTUVWXYZ???? ";
const iterations = 1e1;
let a;
let s;
let i;
function string2array(s) {
return Uint32Array.from(s, (c) => c.codePointAt(0));
}
function array2string(a) {
return String.fromCodePoint(...a);
}
console.time("s2a");
i = iterations;
while (i) {
a = string2array(data);
i -= 1;
}
console.timeEnd("s2a");
console.log(a.toString());
console.time("a2s");
i = iterations;
while (i) {
s = array2string(a);
i -= 1;
}
console.timeEnd("a2s");
console.log(s);
}
testConversions();
【问题讨论】:
-
你可以把你的代码变成一个可运行的sn-p。它在 chrome 中运行良好。
-
为什么需要 Uint32Array ?如果你对 Uint8Array 没问题,那么 TextEncoder 和 TextDecoder API 是 the fastest。
-
.from如何用于类型化数组的概念并不准确。根据MDN documentation,首先收集要进入类型化数组的所有值(使用字符串迭代器和 map 函数),然后使用获得的值的计数创建类型化数组,然后用值填充数组。这可能有助于解释为什么string2array比您预期的要慢。 -
@Traktor53 谢谢你解释了很多。跳过了文档中的那一行……
-
@Kaiido Uint8Array 也很好。我的雷达上没有 TextEncoder。感谢您的提示 - 效果很好。
标签: javascript string performance ecmascript-6 typed-arrays