Updating an item in an array.

Benchmark created on


Description

slice with spread vs map

Setup

/**
 * @param {number} numItems
 */
function makeArray(numItems) {
    const array = [];

    for (let i = 0; i < numItems; i++) {
        array.push({ title: `title${i}`, description: `description${i}` });
    }

    return array;
}

/**
 * @param {number} index
 * @param {any} updatedItem
 * @param {any[]} array
 */
function updateArrayWithMap(index, updatedItem, array) {
    const newModules = array.map((module, i) => {
        if (i === index) {
            return updatedItem;
        }
        return module;
    });
    return newModules;
}

/**
 * @param {number} index
 * @param {any} updatedItem
 * @param {any[]} array 
 */
function updateArrayWithSlice(index, updatedItem, array) {
    const newModules = [...array.slice(0, index), updatedItem, ...array.slice(index + 1)];
    return newModules;
}

const array10 = makeArray(10)
const array100 = makeArray(100)
const array1000 = makeArray(1000)
const array10000 = makeArray(10000)
const array100000 = makeArray(100000)

Test runner

Ready to run.

Testing in
TestOps/sec
With Map with 10 items
updateArrayWithMap(7, {title: 'updatedTitle', description: 'updatedDescription'}, array10)
ready
With Slice with 10 items
updateArrayWithSlice(7, {title: 'updatedTitle', description: 'updatedDescription'}, array10)
ready
With Map with 100 items
updateArrayWithMap(70, {title: 'updatedTitle', description: 'updatedDescription'}, array100)
ready
With Slice with 100 items
updateArrayWithSlice(70, {title: 'updatedTitle', description: 'updatedDescription'}, array100)
ready
With Map with 1000 items
updateArrayWithMap(700, {title: 'updatedTitle', description: 'updatedDescription'}, array1000)
ready
With Slice with 1000 items
updateArrayWithSlice(700, {title: 'updatedTitle', description: 'updatedDescription'}, array1000)
ready
With Map with 10000 items
updateArrayWithMap(7000, {title: 'updatedTitle', description: 'updatedDescription'}, array10000)
ready
With Slice with 10000 items
updateArrayWithSlice(7000, {title: 'updatedTitle', description: 'updatedDescription'}, array10000)
ready
With Map with 100000 items
updateArrayWithMap(70000, {title: 'updatedTitle', description: 'updatedDescription'}, array100000)
ready
With Slice with 100000 items
updateArrayWithSlice(70000, {title: 'updatedTitle', description: 'updatedDescription'}, array100000)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.