end()/atEnd() to allow only negative index for more efficiency than at()

array[array.length-1] is not that easy when deal with array returned by a function, but with end(), it will be simple like array.filter(...).end(-1)

But it's not that hard. The point I'm trying to make is if you actually care about the extremely minor performance impact of this in a certain area of your code, then you're probably doing all sorts of unreadable things. For example, you would use a c-style loop for (let i = 0; i < length; ++i) instead of a for-of loop because those are faster, and you would use ~~ instead of Math.floor(), and to check if something is an array, you would do yourArray.constructor === Array instead of Array.isArray(yourArray), and you wouldn't use .filter(), .map(), or .reduce() like you just mentioned, as for loops are much faster than those, and you would inline as many functions as possible (function calls aren't free), and you would write extremly-difficult-to-read-and-understand branchless code, if you're using any libraries in that section of code, then maybe you'll handwrite the portions you need so you can squeeze out some extra performance, etc.

But that's not all - the biggest performance hits often come from locallity issues, not from these tiny micro-optimizations, so you might take a look at restructuring how you're doing things in uglier way that improve locallity (see here).

At this point, it might be worth just writting this section of code in a different language and compiling it to WebAssembly instead, as you'll get much better performance out of that.

(note that I keep talking about a section of code. No one should micro-optimize an entire application, only the parts that need it most. If you micro-optimizae an on-click handler, would the end user ever notice the difference? Nope. It doesn't need it, so don't make code unreadable and bug prone to give something they don't need).

The point is, it's unreasonable to complain about the performance of array.at() unless you're actually writing code that's doing all sorts of unreadable micro-optimizations as described above, many of which create a much bigger performance improvement. If you're not, then you don't have a use case for an ever-so-slightly faster version of array.at(). If you are, then using array[array.length - 1] shouldn't add much relative unreadability compared to the rest of the gross stuff being done (and it's possible a browser could optimize array[array.length - 1] to be just as fast as array.end(-1) - I don't know for sure`)

2 Likes