> -1 vs. != -1 vs. bitwise NOT (~)

Benchmark created by Mathias Bynens on


Description

Using ~foo instead of foo > -1 or foo != -1 for functions that may return -1 certainly is neat, but is there a difference in terms of performance?

Inspired by http://www.timmywillison.com/pres/operators/#tilde-useful.

Preparation HTML

<script>
  var str = 'Hello world!',
      match = str.indexOf('o'),
      noMatch = str.indexOf('a');
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
> -1 when there’s a match
match > -1;
ready
!= -1 when there’s a match
match != -1;
ready
Bitwise NOT (~) when there’s a match
~match;
ready
> -1, no match
noMatch > -1;
ready
!= -1, no match
noMatch != -1;
ready
Bitwise NOT (~), no match
~noMatch;
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Mathias Bynens on