Skip to content

events.js spliceOne is slower than splice #14081

@Sunqinying

Description

@Sunqinying
  • Version:8.0
  • Platform:mac os

when I inspect the source code of event emitter, I find code and comments in events.js as below:

// About 1.5x 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];
  list.pop();
}

But when test it, I find it's not faster but slower, the test code as below:

let mArr01 = [];
let mArr02 = [];

let length = 10000;

let randData;

for (let i = 0; i < length; i++) {

    randData = Math.random();
    mArr01.push(randData);
    mArr02.push(randData);
}

console.time('Array splice');
for (let j = 0; j < 1000; j++) {
    mArr01.splice(1000 - j, 1);
}
console.timeEnd('Array splice');

console.time('spliceOne splice');
for (let j = 0; j < 1000; j++) {
    spliceOne(mArr02, 1000 - j);
}
console.timeEnd('spliceOne splice');

And I get the result as below:

// first time
Array splice: 3.658ms
spliceOne splice: 18.979ms

// second time
Array splice: 4.846ms
spliceOne splice: 27.892ms

// third time
Array splice: 3.274ms
spliceOne splice: 21.974ms

so, Is there any reason for old version ? Or any other reasons?

Metadata

Metadata

Assignees

No one assigned

    Labels

    eventsIssues and PRs related to the events subsystem / EventEmitter.performanceIssues and PRs related to the performance of Node.js.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions