phuocng/1loc

Checking for an empty array can be faster

inoyakaigor opened this issue · 5 comments

I made a simple performance test and it shows that getting length of array keys is not optimal code. I propose change it to a.filter(Boolean).length > 0. This code can be faster from 4.5 (Firefox) or 5.9 (Chrome) to 26 (Safari) times.

image

Hey Igor, that is a really good insight.

However, as you probably know, this is not universal. There could be valid falsy values in the array, like ['', 0]. Which this would mark as empty.

However, seeing how fast a.lenght is, maybe it makes sense to add this before the keys check, WDYT?

Yeah, exactly, falsy. How I could forget!
I think there is still need filter function and therefore I suppose better solution wich cover edge cases is

Array.isArray(a) && a.length > 0 && a.filter(el => el === undefined)

Also checking can be faster if use latest ES2020 feature (link):
image

For history: my jsperf test from initial message https://jsperf.com/object-keys-vs-array-length

Can you make a PR?

Yes of course