Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

prefer-set-has: Add option for number of elements required #2473

Closed
RebeccaStevens opened this issue Oct 8, 2024 · 2 comments
Closed

prefer-set-has: Add option for number of elements required #2473

RebeccaStevens opened this issue Oct 8, 2024 · 2 comments

Comments

@RebeccaStevens
Copy link

Description

From the docs:

Set#has() is faster than Array#includes().

This is only true for sets containing a larger number of elements. For a small number of elements, using array.includes is both faster for look-ups, and has a smaller memory footprint.

I would like to propose adding an option to this rule to specify how many elements are needed before this rule kicks in. Additionally, it would be nice if the rule enforced using an array over a set when this threshold isn't met.

I suggest the name threshold for this option.
If this option were to be enabled by default, then the default should probably be somewhere between 10 and 30.

Fail

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const hasValue = value => array.includes(value);
const set = new Set([1, 2, 3]);
const hasValue = value => set.has(value);

Pass

const array = [1, 2, 3];
const hasValue = value => array.includes(value);
const set = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
const hasValue = value => set.has(value);

Additional Info

No response

@sindresorhus
Copy link
Owner

This is only true for sets containing a larger number of elements. For a small number of elements, using array.includes is both faster for look-ups, and has a smaller memory footprint.

Source?

@RebeccaStevens
Copy link
Author

RebeccaStevens commented Oct 8, 2024

My statement was based on this being the fact in C code.

I wrote a benchmark to test this, but it seems that the statement doesn't hold in JavaScript (at least in node v22.9 where I tested).

HashSets have some overhead (like needing to calculate the hash value of the object) before they can do their lookup; which arrays don't have. Arrays also have the advantage of speculative execution (something that my computer may not be new enough to take advantage of) working in their favor.
I assumed JS Sets were just HashSets and thus I could carry the same logic over, but maybe they work a little differently. Or maybe something else is at play.

@RebeccaStevens RebeccaStevens closed this as not planned Won't fix, can't repro, duplicate, stale Oct 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants