diff --git a/benchmark/util/splice-one.js b/benchmark/util/splice-one.js new file mode 100644 index 00000000000000..5c2a39f6d72a11 --- /dev/null +++ b/benchmark/util/splice-one.js @@ -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); +} diff --git a/lib/internal/util.js b/lib/internal/util.js index 071563a737815b..07515e2e090daa 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -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(); } diff --git a/test/parallel/test-benchmark-util.js b/test/parallel/test-benchmark-util.js index 9a6ae370b7d312..838e51daac26b4 100644 --- a/test/parallel/test-benchmark-util.js +++ b/test/parallel/test-benchmark-util.js @@ -10,6 +10,8 @@ runBenchmark('util', 'method=Array', 'n=1', 'option=none', + 'pos=start', + 'size=1', 'type=', 'version=native'], { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });