I wanted to benchmark the function that I am using to find out if there is a duplicated attribute in an array of objects using map()
and some()
versus another function that does the same thing but using a for()
inside another for()
.
let array = [ { "value": 41}, { "value": 12}, { "value": 32} ];
let itens = array.map(x => x.value);
let haveDuplicate = itens.some((item, idx) => itens.indexOf(item) !== idx);
versus:
let array = [ { "value": 41}, { "value": 12}, { "value": 32} ];
let haveDuplicate = false;
for (let i = 0; i < array.length; i++) {
let x = array[i];
for (let j = (i + 1); j < array.length; j++) {
if (array[j]) {
let y = array[j];
if (x.value === y.value) {
haveDuplicate = true;
return;
} else {
haveDuplicate = false;
}
}
}
}
Using JsPerf I can see that the function that uses map()
and some()
runs 90% ~ 100% slower.
Click here to check the benchmark
Can someone explain to me why?
EDIT: this question is duplicate of this one: Why most JavaScript native functions are slower than their naive implementations?