Javascript Performance Tips

Iqbal Novramadani
2 min readOct 4, 2020

Array map is one of the most used method in today’s Javascript world. But sometimes developers use this method blindly out of habit to update single value inside an array.

This is more often happens if we store our data in React state or Redux store, because naturally it’s easy to render them when they are in array form in many cases.

There are three approaches we can do.

// 1st approach use array map
console.time('first')
let arr = [1, 2, 3, 4, 5]
arr = arr.map(v => {
if (v === 4) return v * 2
return v
})
console.timeEnd('first')
// 2nd approach use findIndex
console.time('second')
let arr2 = [1, 2, 3, 4, 5]
const idx = arr2.findIndex(v => v === 4)
arr2[idx] = arr2[idx] * 2
console.timeEnd('second')
// 3rd approach use object and convert to array
console.time('third')
const obj3 = {
[1]: 1,
[2]: 2,
[3]: 3,
[4]: 4,
[5]: 5
}
obj3[4] = obj3[4] * 2
const arr3 = Object.keys(obj3).map(v => obj3[v])
console.timeEnd('third')

We can use console.time and console.timeEnd to capture the execution time in Javascript code. Give it a label then it can recognize how to differentiate one another.

Let’s see how the three approaches perform.

Execution time of the three approaches

Now it’s clear that it’s faster using the findIndex approach. It makes sense, when we need to update a value inside an array, it’s faster to update that index only. Rather than mapping through the whole array length. Even the third approach is better than the first one.

For one operation it might be 0.03 ms difference. But imagine if our app has many logic using this kind of update. Moreover if the logic is being called in every UI render. We will find performance boost only with this simple approach.

A little note for the third approach, it is usually applicable for data like below.

// array approach of storing data
// fast to render but long time to update
[
{ id: 'adsfjh12937',
name: 'first'
//...other fields
},
{ id: 'adsfjh12933',
name: 'second',
//...other fields
},
//...other values
]
// object approach of storing data
// use the id or any appropriate info for the keys
// fast to update but needs time to render because need to convert to array
{
'adsfjh12937': {
id: 'adsfjh12937',
name: 'first',
//...other fields
},
'adsfjh12933': {
id: 'adsfjh12933',
name: 'first',
//...other fields
},
}

You can use object approach instead of array when you know update operations happen more often than read/render. And vice versa.

Finally, if you know another faster approaches, please let us (me and the readers) know in the comments section. We would always love to know how we can make our code optimized, more performant and runs faster.

And thanks for reading!

--

--

Iqbal Novramadani

Muslim, servant of humanity, business and technology enthusiast. Discuss with me anything about Islam! and maybe software. :)