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 <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>
1 parent 58a65d6 commit e854c95

3 files changed

Lines changed: 39 additions & 3 deletions

File tree

‎benchmark/util/splice-one.js‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'use strict';
2+
3+
constcommon=require('../common');
4+
5+
constbench=common.createBenchmark(main,{
6+
n: [1e7],
7+
pos: ['start','middle','end'],
8+
size: [10,100,500],
9+
},{flags: ['--expose-internals']});
10+
11+
functionmain({ n, pos, size }){
12+
const{ spliceOne }=require('internal/util');
13+
constarr=newArray(size);
14+
arr.fill('');
15+
letindex;
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(vari=0;i<n;i++){
29+
spliceOne(arr,index);
30+
arr.push('');
31+
}
32+
bench.end(n);
33+
}

‎lib/internal/util.js‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -322,10 +322,11 @@ function join(output, separator) {
322322
returnstr;
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
functionspliceOne(list,index){
327-
for(vari=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‎

Lines changed: 2 additions & 0 deletions
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)