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]
let last = data[data.length - 1]
let last = [...data].pop()
let last = data.reduceRight(x => x)
let last = data.at(-1)
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]
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)
and
let last = [...data].pop()
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)