DEV Community

Discussion on: Big-O Notation Cheatsheet

Collapse
 
qm3ster profile image
Mihail Malo • Edited

And WOW, creating the array at the correct size really makes a huge difference:

function buildSquareMatrix2(items) {
    const len = items.length
    let matrix = new Array(len)

    for (let i = 0; i < len; i++) {
        const next = new Array(len)

        for (let j = 0; j < len; j++) {
            next[j] = items[j]
        }

        matrix[i] = next
    }
    return matrix
}
buildSquareMatrix        9504
buildSquareMatrix2       1528
buildSquareMatrix3       678

Less than 3x slowdown over .slice() while still allowing you to modify each value!