2017-05-09 7 views
1

ES6で文字列をTypedArraysに変換してからStringに戻す必要があります。 は現在、これには以下の機能で行われます。StringをUint32Arrayに変換するときのパフォーマンス

function string2array(s) { 
    return Uint32Array.from(s, (c) => c.codePointAt(0)); 
} 

function array2string(a) { 
    return String.fromCodePoint(...a); 
} 

string2arrayarray2stringより2倍遅いです。私は両方の機能が同等に速くなることを期待していました。彼らがどのように働くかについての私の考えは次の通りです:

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 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; 
 
    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();

+0

コードを実行可能スニペットにすることができます。それはクロムで正常に動作します。 – Tschallacka

+0

なぜUint32Arrayが必要ですか?あなたがUint8ArrayでOKなら、[TextEncoder](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder)と[TextDecoder](https://developer.mozilla。 APIは[最も速い](https://jsperf.com/str2array-vs-textencoder/1)です。 – Kaiido

+0

型付き配列の '.from'がどのように機能するかという概念的な考え方は正確ではありません。 [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from#Description)では、まず、型付き配列に入るすべての値が収集されます文字列イテレータとマップ関数を使用して)、得られた値のカウントを使用して型付き配列が作成され、配列に値が移入されます。これはなぜ 'string2array'があなたが期待したよりも遅いのかを説明するのに役立ちます。 – traktor53

答えて

0

あなたstring2array以上array2stringをやっているので、あなたのテストは異なるlilのでなければなりません。

あなたが作成した場合: string_2_code_point_array code_point_array_2_uint_array uint_array_2_string あなたは最後の二つは同等の時間を持っていることがわかります。

関連する問題