DEV Community

Discussion on: Stop Writing JavaScript Like This

Collapse
 
pedro profile image
Pedro M. M. • Edited

I agree that this is premature optimization and for a simpler reason: This use case can't be a hot-path because you always will have a small list and even in the case that it is a hot-path you will end up using a database if the list grows too much, so by that time you won't be using hard-coded variables anyway.

But I'd like to point out (not for you, but anyone reading this) that 'includes' itself time complexity IS linear O(n), as described in the spec (Step 10, tc39.es/ecma262/#sec-array.prototy... ):

Let O be ? ToObject(this value).
2. Let len be ? LengthOfArrayLike(O).
3. If len is 0, return false.
4. Let n be ? ToIntegerOrInfinity(fromIndex).
5. Assert: If fromIndex is undefined, then n is 0.
6. If n is +∞, return false.
7. Else if n is -∞, set n to 0.
8. If n ≥ 0, then
    a. Let k be n.
9. Else,
    a. Let k be len + n.
    b. If k < 0, set k to 0.
10. Repeat, while k < len,
    a. Let elementK be ? Get(O, ! ToString(𝔽(k))).
    b. If SameValueZero(searchElement, elementK) is true, return true.
    c. Set k to k + 1.
11. Return false.
Enter fullscreen mode Exit fullscreen mode

It just happens to be constant in this case because our data initialization: the array is hard-coded, so it is a fixed constant (as you noted in your article), but the algorithm of the method by itself is O(n) in the scope of the algorithm (and because the worst case for the algorithm is not fixed data initialization I would still say that this is O(n) in a wider scope IMO, just in case we change our data initialization in the future which is not that uncommon).

I just wanted to clarify that to avoid any distracted developers reading this to misleadingly think that 'includes' is O(1) because it uses some kind of hash table.

And yeah, this is premature optimization.

Edit. Fix spec link.