Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

util: improve spliceOne perf #20453

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions benchmark/util/splice-one.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict';

const common = require('../common');

const bench = common.createBenchmark(main, {
n: [1e7],
size: [10, 100, 500],
}, { flags: ['--expose-internals'] });

function main({ n, size, type }) {
const { spliceOne } = require('internal/util');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curious, why put this here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The benchmark runs with --expose-internals so the main function has access to them but the outside doesn't.

const arr = new Array(size);
arr.fill('');
const pos = Math.floor(size / 2);

bench.start();
for (var i = 0; i < n; i++) {
spliceOne(arr, pos);
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