Reputation: 1629
I have the following 2 functions:
//destructive
const getEveryX = (arr, x, offset) => {
const _arr = [...arr];
let _arrArr = [];
if (offset && offset >= arr.length) {
_arrArr.push(_arr.splice(0, offset));
}
while (_arr.length > x) {
_arrArr.push(_arr.splice(0, x));
}
if (_arr.length) {
_arrArr.push(_arr);
}
return _arrArr
}
and
//copying
const getEveryX2 = (arr, x, offset) => {
let _pointer = 0;
const _arrArr = [];
if (offset && offset >= arr.length) {
_arrArr.push(arr.slice(0, offset));
}
while (arr.length >= _pointer + x) {
_arrArr.push(arr.slice(_pointer, _pointer + x));
_pointer += x;
}
if (arr.length) {
_arrArr.push(arr.slice(_pointer, arr.length - 1));
}
return _arrArr;
};
I wrote the second function because I thougt it would be faster to copy the parts I need from the original array instead of copying the original and splicing out the beginning every time (both functions should do the same, first uses splice, second slice) - I tested it and this doesnt seem to be the case, they both take the same time.
My theory is that the compiler knows what I want to do in both cases and creates the same code. I could also be completely wrong and the second version shouldnt be faster without optimizations.
Do you know what is going on here?
Upvotes: 0
Views: 70
Reputation: 665574
I tested it and this doesnt seem to be the case, they both take the same time.
No, your test case is broken. JSperf doesn't run setup and teardown for each of your snippets runs, it runs a your snippets in a loop between setup and teardown. You are emptying the testArr
on the first run, the rest of the iterations only measures the while (testArr.length > 1)
condition evaluation (yielding false
).
I've updated the benchmark, and as expected slice
is now performing better.
Upvotes: 1