util: improve spliceOne perf

Do less variable allocations and reassignments inside spliceOne
since it's relied on by some performance sensitive code.

PR-URL: https://github.com/nodejs/node/pull/20453
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Tobias Nießen <tniessen@tnie.de>
Reviewed-By: Tiancheng "Timothy" Gu <timothygu99@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Daniel Bevenius <daniel.bevenius@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
This commit is contained in:
Anatoli Papirovski 2018-05-01 14:22:39 +02:00
parent fe8794560a
commit b04d0921ae
No known key found for this signature in database
GPG Key ID: 614E2E1ABEB4B2C0
3 changed files with 39 additions and 3 deletions

View File

@ -0,0 +1,33 @@
'use strict';
const common = require('../common');
const bench = common.createBenchmark(main, {
n: [1e7],
pos: ['start', 'middle', 'end'],
size: [10, 100, 500],
}, { flags: ['--expose-internals'] });
function main({ n, pos, size }) {
const { spliceOne } = require('internal/util');
const arr = new Array(size);
arr.fill('');
let index;
switch (pos) {
case 'end':
index = size - 1;
break;
case 'middle':
index = Math.floor(size / 2);
break;
default: // start
index = 0;
}
bench.start();
for (var i = 0; i < n; i++) {
spliceOne(arr, index);
arr.push('');
}
bench.end(n);
}

View File

@ -322,10 +322,11 @@ function join(output, separator) {
return str;
}
// About 1.5x faster than the two-arg version of Array#splice().
// As of V8 6.6, depending on the size of the array, this is anywhere
// between 1.5-10x faster than the two-arg version of Array#splice()
function spliceOne(list, index) {
for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
list[i] = list[k];
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}

View File

@ -10,6 +10,8 @@ runBenchmark('util',
'method=Array',
'n=1',
'option=none',
'pos=start',
'size=1',
'type=',
'version=native'],
{ NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });