The difference was so clear, that I tested them in many ways, and even inverted the call to make sure it wasn't a garbage collector problem or so.

NodeJS is not magic, and you are not a Wizard

Ivan Seidel Gomes

593

I think this benchmark is invalid. You allocate memory and call `Math.random()` inside your test case. That is you measure the time needed for these operations as well. The time required for these operations may be greater than the time required for the tested operation itself.

Anyhow, I ran your test at least 10 times and I constantly get results similar to:

Stress test on sumVectorObject: 7704 ms

Stress test on sumVectorArray: 5401 ms

I changed your tests such that first the input data is allocated and initialized and then the functions run on this data and I got the following result:

Stress test on sumVectorObject2: 1202 ms

Stress test on sumVectorArray2: 193 ms

Note: I had to reduce the input data size from 10M to 5M.

The updated test code:

const sumVectorObject2 = (a, b) => {

let c = {x: a.x + b.x, y: a.y + b.x}

return c;

}

// As Array

const sumVectorArray2 = (a, b) => {

let c = [a[0] + b[0], a[1] + b[1]]

return c;

}

function makeItBurn2(name, benchMethod, input) {

let timeStart = Date.now()

let N = input.length/2;

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

benchMethod(input[i], input[i+1]);

}

let timeEnd = Date.now()

let duration = (timeEnd — timeStart)

console.log(`Stress test on ${name}: ${duration} ms`)

}

const N = 5 * 1000 * 1000;

let arrInput = [];

let objInput = [];

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

let a = {x: Math.random(), y: Math.random()};

let b = {x: Math.random(), y: Math.random()};

arrInput.push([a.x, a.y]);

arrInput.push([b.x, b.y]);

objInput.push({x:a.x, y:a.y});

objInput.push({x:b.x, y:b.y});

}

makeItBurn2(‘sumVectorObject2’, sumVectorObject2, objInput);

makeItBurn2(‘sumVectorArray2’, sumVectorArray2, arrInput);