【问题标题】:Performance when converting a String to Uint32Array将字符串转换为 Uint32Array 时的性能
【发布时间】: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);
}

string2arrayarray2string 慢两倍。我希望这两个功能同样快。我对它们如何工作的概念如下:

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

所以他们看起来和我相当。

  1. 为什么 string2array 比较慢?
  2. 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 没问题,那么 TextEncoderTextDecoder API 是 the fastest
  • .from 如何用于类型化数组的概念并不准确。根据MDN documentation,首先收集要进入类型化数组的所有值(使用字符串迭代器和 map 函数),然后使用获得的值的计数创建类型化数组,然后用值填充数组。这可能有助于解释为什么 string2array 比您预期的要慢。
  • @Traktor53 谢谢你解释了很多。跳过了文档中的那一行……
  • @Kaiido Uint8Array 也很好。我的雷达上没有 TextEncoder。感谢您的提示 - 效果很好。

标签: javascript string performance ecmascript-6 typed-arrays


【解决方案1】:

您的测试应该有所不同,因为您 string2array 所做的比 array2string 更多。

如果您创建: string_2_code_point_array code_point_array_2_uint_array uint_array_2_string 你会看到最后两个有可比的时间。

【讨论】:

    猜你喜欢
    • 2014-02-12
    • 2020-06-05
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    • 2021-08-12
    相关资源
    最近更新 更多