Tests:
  • For-loop approach test

    x
     
    // 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));
Rendered benchmark preparation results:

Suite status: <idle, ready to run>

Previous results

Experimental features:

  • Test case name Result
    For-loop approach test
    Native functions test

    Fastest: N/A

    Slowest: N/A

Latest run results:
Run details: (Test run date: 2 years ago)
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36
Chrome 103 on Mac OS X 10.15.7
View result in a separate tab
Test name Executions per second
For-loop approach test 34778.5 Ops/sec
Native functions test 36504.1 Ops/sec