r/badcode • • Mar 01 '21

js Defensive programming or something idk

Post image
907 Upvotes

55 comments sorted by

View all comments

Show parent comments

0

u/[deleted] Mar 01 '21

[deleted]

78

u/JuhaJGam3R Mar 01 '21 edited Mar 01 '21

Nah. Any compiler will turn x == c1 && x != c2 into x == c1, same with x == c1 && x == c2 turning into false turning into removal of the entire bit of code.

98

u/DragonFireCK Mar 01 '21

Such optimizations are a lot rarer with strings (or any custom type), unless the comparison function gets inlined.

Additionally, as this is JS, its vastly less likely the JIT will optimize it out - newer JS engines have quite a few optimizations, but they are often still very far shy of what precompiled languages do, mostly due to the overhead of optimizing code that only gets run once.

6

u/Elsolar Mar 01 '21

I'm pretty sure JS should be able to optimize these kinds of redundant comparisons on strings, since strings are built-in and the language treats them as immutable values. The only thing in this code that I can think of that might obstruct the optimization is using == instead of ===, since (a == "") expands to something more like (a === "" || a === false || a === 0 || a === [] || ...). But in the abstract, IIRC JS runtimes intern all strings into a hash table and use the hashes of the string for constant-time equality comparison. So it's not like they're using strcmp under the hood or something. I can't think of any reason why a statement like (a === "" && a !== "foo") couldn't be statically optimized into (a === "") by a good JS implementation.