DEV Community

Cover image for Ideas on improving array element access and making web apps performant
Saura
Saura

Posted on

Ideas on improving array element access and making web apps performant

Tiny things matter when it comes to the performance of a web application.

Let's take a very intuitive problem where we wonder how web developers will access the last element from an array of items that contains ~1 million items in it.

The obvious thoughts are using the slice, pop array methods or via accessing the index or in many other ways below:-

let data = [...] => ~millions of items.

let last = data.slice(-1)[0]
Enter fullscreen mode Exit fullscreen mode
let last = data[data.length - 1]
Enter fullscreen mode Exit fullscreen mode
let last = [...data].pop()
Enter fullscreen mode Exit fullscreen mode
let last = data.reduceRight(x => x)
Enter fullscreen mode Exit fullscreen mode
let last = data.at(-1)
Enter fullscreen mode Exit fullscreen mode

or by using external libraries like lodash and any jQuery methods.

After running some tests on these sets of instructions for an array of millions of items we have got a performance benchmark!

Conclusions - It's recommended to use

let last = data[data.length - 1]
Enter fullscreen mode Exit fullscreen mode

which is the fastest cross-browser solution among all possible solutions.
After that my personal choice will be to use

let last = data.at(-1)
Enter fullscreen mode Exit fullscreen mode

and

let last = [...data].pop()
Enter fullscreen mode Exit fullscreen mode

Although, [...data].pop() takes an extra space of O(N) and time to create a shallow copy of the big data array but it's faster.
Solutions using jQuery are the slowest on all browsers.
Thanks to StackOverflow and Kamil Kiełczewski.

Top comments (0)