Reputation: 87
I was trying to insert an element in the array at the given index. Naturally, I found myself leaning on to the native methods provided by JavaScript. However, when I tried to achieve the same result, but this time using custom logic, I found some performance differences. So, my question is do you think it matters and does it make sense to use custom logic more often? Also, if you know a faster way to insert an element in the array, please share.
The setup:
Initial code using Array.prototype.slice, Array.prototype.push and Array.prototype.concat :
// Params:
const arr = [1, 2, 3, 4];
const index = 3;
const newItem = 5;
// Steps:
// 1. Create new array from the original one at given index
let start = arr.slice(0, index);
// 2. Add new item to the copy
start.push(newItem);
// 3. Get the rest of the original array
let end = arr.slice(index);
// 4. Print the merged array
console.log(start.concat(end));
Custom approach using for loops:
// Params:
const arr = [1, 2, 3, 4];
const index = 3;
const newItem = 5;
// Steps:
// 1. Create new array from the original one at given index
let copy = [];
for (let i = 0; i < index; i++) {
copy[copy.length] = arr[i];
}
// 2. Add new item to the copy
copy[index] = newItem;
// 3. Get the rest of the original array
let rest = [];
for (let i = index; i < arr.length; i++) {
rest[rest.length] = arr[i];
}
// 4. Merge the two arrays
for (let i = 0; i < rest.length; i++) {
copy[copy.length] = rest[i];
}
// 5. Print the merged array
console.log(copy);
Moreover, this is a link to the benchmark, I have created: https://measurethat.net/Benchmarks/ShowResult/317820
In summary, the results are:
The difference might not seem so big at first glance, but when we account for the daily load, It might be significant in some cases I believe. Anyway, tell me what do you think? Is this a fair battle or should I approach the situation differently?
Upvotes: 0
Views: 101
Reputation: 181745
There are several issues with your benchmark:
It measures performance of setup code and console.log
as well. Especially logging in a tight loop like this can be quite slow. You can use e.g. https://jsbench.me/ to put setup code outside the benchmarked code.
The array is far too small to show a meaningful difference.
If I pull out the setup code, remove logging, increase the array size to 1000 and insert an element at index 500, your custom approach is about 15% slower (Firefox 102, Arch Linux x86_64 on Intel i7 920).
And there is a better built-in method too: Array.splice
. It modifies the array in-place, so it doesn't need to copy the first portion (unless the growth requires the array to reallocate). But if you need the copy (like for a fair benchmark):
const copy = Array.from(arr);
copy.splice(index, 0, newItem);
This approach is the fastest of the three, and more importantly, also the most readable.
Upvotes: 2