Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
Run results for:
Insert value at certain index in array
The goal is to test which is faster - combinations between Array.prototype.slice and Array.prototype.push methods or custom for-loop alternative in the context of inserting value at given index
Go to the benchmark
Embed
Embed Benchmark Result
Run details:
User agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:147.0) Gecko/20100101 Firefox/147.0
Browser:
Firefox 147
Operating system:
Windows
Device Platform:
Desktop
Date tested:
2 months ago
Test name
Executions per second
For-loop approach test
144800.6 Ops/sec
Native functions test
142317.1 Ops/sec
Tests:
For-loop approach test
// 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);
Native functions test
// 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));