2

Given this JSPerf test

Why is this faster

var x;var i = 1E4;var j = 1E4;
for (; i-- > -1;) {
  x = -~x;
}
for (; j-- > -1;) {
  x = ~ - x;
}

Than this ?

var x;var i = 1E4;var j = 1E4;
for (; j-- > -1;) {
  x = -1 * ~x;
}
for (; j-- > -1;) {
  x = ~ (-1 * x);
}

Is the second version better optimizable, or what is the reason?

Moritz Roessler
  • 8,542
  • 26
  • 51

2 Answers2

1

I believe that in the second test you are either forgetting to reset j to 1E4, or you meant to use an i in one of the loops. See this test:

http://jsperf.com/bit-increment/2

I added a snippet using i in the first loop and j in the second and it performs just as fast as the first test.

imreal
  • 10,178
  • 2
  • 32
  • 48
1

In the second code sample, you use j as the iterator in both loops.

osbomb
  • 34
  • 4