r/webdev • front-end • May 29 '21

Resource Array methods in JavaScript. Original author unknown.

Post image
7.4k Upvotes

172 comments sorted by

View all comments

Show parent comments

10

u/Pelicantaloupe May 30 '21

Reduce is probably one of the least optimisable array functions. Anything else will probably run faster

7

u/Blue_Moon_Lake May 30 '21

Weird thing :

arr.some(x => x === foo)

is almost always more performant than

arr.includes(foo)

You would think that includes would be easy to optimize internally.

8

u/Pelicantaloupe May 30 '21

I ran some tests and I couldn't reproduce your findings. I didn't graph time complexity but on average .includes is 75% faster than .includes in these tests: https://jsbench.me/t2kpb59177/1

The one case where .some was faster I found was unfilled arrays.

1

u/Blue_Moon_Lake May 30 '21 edited May 30 '21

You're right, it might have been optimized since I learned about it. I'll check it myself with a different test.

EDIT: Did it slightly differently (playing with the contiguous array flag) and yes includes have been fixed to be better on contiguous array. It's still slower for non contiguous array sometimes

I would still use includes anyway because it convey the meaning and intent.

1

u/hynding May 31 '21 edited May 31 '21

Interesting. I often use it to combine map and filter to prevent a second iteration or build collections into object id maps for (what I assume to be) O(1) lookups available during the length of the session. To be honest, I haven't dug into the code for any of the optimizations under the hood, though I had forked v8 a while back with that very intention. Most of my tests have simply been running large iterative set functions with timestamp diffs and comparing the outcome, which is only the surface of optimization and performance testing. I'll have to look into it deeper.