eterps
eterps

Reputation: 14208

Is (!~index) faster than (index === -1)?

Every so often I run across someone using (!~val) instead of (val === -1) in situations where -1 is returned from a function (e.g. indexOf()).

To me, the logical NOT + bitwise NOT statement seems horribly unreadable when compared to the -1 comparison. Is there enough of a speed difference to warrant using one over the other? Or if not speed, some other reason that I'm missing to use a bitwise NOT instead of === ?

(Aplologies in advance if this is a dup., but I couldn't find an answer to this exact question. Searching for "!~" doesn't quite work in SO or Google)

Upvotes: 3

Views: 101

Answers (3)

Dave Newton
Dave Newton

Reputation: 160181

Is it a meaningful performance difference? Likely not, but it depends entirely on the VM.

You can always find out using something like http://jsperf.com/

Upvotes: 1

Robert Koritnik
Robert Koritnik

Reputation: 105019

Be pragmatic, go for readability

Both are f@$# off fast.

If your script has performance issues it definitely won't boil down to this boolean check. But as others have stated these two are not (completely) the same.

Upvotes: 0

njr101
njr101

Reputation: 9619

No, they are definitely not the same.

The bitwise conversion will do an implicit type coercion. The === operator checks for type equality.

So these these two can give completely different results.

var val = "-1";

(!~val) // true
(val === -1)  // false

In a situation like this I think the intent and correctness of the comparison far outweighs any performance consideration. Decide what exactly you want to compare and use the right comparison for the job.

Upvotes: 3

Related Questions