DEV Community

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

Posted on

1 1

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.

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Jetbrains image

Is Your CI/CD Server a Prime Target for Attack?

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. It makes sense—CI/CD servers have access to source code, a highly valuable asset. Is yours secure? Check out nine practical tips to protect your CI/CD.

Learn more