Skip to content

Commit

Permalink
util: improve spliceOne perf
Browse files Browse the repository at this point in the history
Do less variable allocations and reassignments inside spliceOne
since it's relied on by some performance sensitive code.

PR-URL: #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>
  • Loading branch information
apapirovski authored and MylesBorins committed May 8, 2018
1 parent 58a65d6 commit e854c95
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
33 changes: 33 additions & 0 deletions benchmark/util/splice-one.js
Original file line number Diff line number Diff line change
@@ -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);
}
7 changes: 4 additions & 3 deletions lib/internal/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand Down
2 changes: 2 additions & 0 deletions test/parallel/test-benchmark-util.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ runBenchmark('util',
'method=Array',
'n=1',
'option=none',
'pos=start',
'size=1',
'type=',
'version=native'],
{ NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });

0 comments on commit e854c95

Please sign in to comment.