Skip to content

Commit e854c95

Browse files
apapirovskiMylesBorins
authored andcommitted
util: improve spliceOne perf
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 <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Tobias Nießen <[email protected]> Reviewed-By: Tiancheng "Timothy" Gu <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Daniel Bevenius <[email protected]> Reviewed-By: Trivikram Kamat <[email protected]>
1 parent 58a65d6 commit e854c95

File tree

3 files changed

+39
-3
lines changed

3 files changed

+39
-3
lines changed

benchmark/util/splice-one.js

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
5+
const bench = common.createBenchmark(main, {
6+
n: [1e7],
7+
pos: ['start', 'middle', 'end'],
8+
size: [10, 100, 500],
9+
}, { flags: ['--expose-internals'] });
10+
11+
function main({ n, pos, size }) {
12+
const { spliceOne } = require('internal/util');
13+
const arr = new Array(size);
14+
arr.fill('');
15+
let index;
16+
switch (pos) {
17+
case 'end':
18+
index = size - 1;
19+
break;
20+
case 'middle':
21+
index = Math.floor(size / 2);
22+
break;
23+
default: // start
24+
index = 0;
25+
}
26+
27+
bench.start();
28+
for (var i = 0; i < n; i++) {
29+
spliceOne(arr, index);
30+
arr.push('');
31+
}
32+
bench.end(n);
33+
}

lib/internal/util.js

+4-3
Original file line numberDiff line numberDiff line change
@@ -322,10 +322,11 @@ function join(output, separator) {
322322
return str;
323323
}
324324

325-
// About 1.5x faster than the two-arg version of Array#splice().
325+
// As of V8 6.6, depending on the size of the array, this is anywhere
326+
// between 1.5-10x faster than the two-arg version of Array#splice()
326327
function spliceOne(list, index) {
327-
for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
328-
list[i] = list[k];
328+
for (; index + 1 < list.length; index++)
329+
list[index] = list[index + 1];
329330
list.pop();
330331
}
331332

test/parallel/test-benchmark-util.js

+2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ runBenchmark('util',
1010
'method=Array',
1111
'n=1',
1212
'option=none',
13+
'pos=start',
14+
'size=1',
1315
'type=',
1416
'version=native'],
1517
{ NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });

0 commit comments

Comments
 (0)