目前,使用Buffer / Uint8Array而不是普通数组有明显的性能优势吗?

时间:2017-04-14 15:45:19

标签: javascript node.js performance

我相信,现在,像V8这样的JavaScript引擎始终能够检测到数组只有0-255范围内的数值,因此将其存储为未装箱的Uint8数组。因此,人们可以预期它们与强类型对应物一样有效。但是,在代码库中使用单个数组类型比使用多个数组类型更方便。

2017年,使用Buffer / Uint8Array而不是普通数组仍然有明显的性能优势吗?

1 个答案:

答案 0 :(得分:0)

请参阅以下用于性能测试的代码using this RunKit。它表明Buffer较慢,这与其他一些历史数据一致。

其他相关数据点:

  1. This jsPerf
  2. This other jsPerf
  3. This older SO thread

    //setup
    //const iNumTests = 1000;
    const iNumTests = 1000;
    let arrResults = [];
    
    function randomChar() {
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    return chars[Math.round(Math.random() * (chars.length - 1))];
    }
    
    function singleTest() {
        //buffer
        const t0 = process.hrtime();
        let buf = Buffer.from(randomChar());  //recommended to initialize with .from()
        for (var i = 1; i < iNumTests; ++i) {
            buf.write(randomChar());
        }
        var sOutput = buf.toString();
        const arrBuff = process.hrtime(t0);
    
        //array
        const t1 = process.hrtime();
        let chars = [];
        for (var i = 0; i < iNumTests; ++i) {
            chars.push(randomChar());
        }
        var sOutput = chars.join('');
        const arrArray = process.hrtime(t1);
    
        //delta
        const timeBuff = arrBuff[0] * 1e9 + arrBuff[1];
        const timeArray = arrArray[0] * 1e9 + arrArray[1];
        return (timeBuff - timeArray);
    }
    
    for (var i = 0; i < iNumTests; i++) {
        arrResults.push(singleTest());
    }
    
    var sum = arrResults.reduce(function(acc, val) {
      return acc + val;
    }, 0);
    
    console.log(sum/iNumTests);         // average difference. I got 146929.598 which means timeBuff is larger on average.