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:
- JavaScript methods: 101170.7 Ops/sec
- Custom approach: 105695.0 Ops/sec
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?