I was reading an article from other website (Computer Science - Can a Minimum Possible Efficiency be proven?) about assuming a minimum Big-O time for the worst cases.
One of the answers goes to a length explaining about the required time to compare binary values (or similar).
And I though to myself: why not bitwise operations?
And I made this mock-up code in Javascript:
console.time('^');
for(var i=0;i<1e5;i++)13^15;
console.timeEnd('^');
console.time('!=');
for(var i=0;i<1e5;i++)13!=15;
console.timeEnd('!=');
And I got really surprised!
The loop using ^
(bitwise-xor) can be almost 3ms faster!
How is this possible?
Why is bitwise-xor (^
) is faster than not-equal (!=
) comparisson?
Other possibly relevant information:
I've tested on Firefox 34.0.5 running on Windows 7 Home Premium x64.
I've also tried this code on Opera 12.17(x64) and Chrome 39.0.2171.95 and the behaviour is almost similar, being the code using ^
faster 80% of the tests.
Another surprise:
In php, running this:
$now=microtime(true);
for($i=0,$x=0;$i<1e6;$i++)$x+=13^15;
echo microtime(true)-$now,PHP_EOL;
$now=microtime(true);
for($i=0,$x=0;$i<1e6;$i++)$x+=13!=15;
echo microtime(true)-$now,PHP_EOL;
Shows exactly the same effect: ^
is faster than !=
.
Using $x+=!13^15;
instead of $x+=13^15;
is faster 70% of the time.
I've tested on http://writecodeonline.com/php/ which is running PHP 5.3 on linux x64.
This code has a suggestion from the user @AlexK., on the following comment:
13^15 is a constant noop, perhaps its simply optimised away (try something effective x+=13^15;)
1e5
to1e6
) I got 457.9ms, 459.2ms and 458.07ms for the^
test, while!=
took 465.91ms (+8.01ms), 469.21ms (+10.01ms) and 469.29ms (+11.22ms). How can I calculate the percentage of these? – Sphenogram13^15
is a constant noop, perhaps its simply optimised away (try something effectivex+=13^15;
) – Abatement13!=15
should be optimized the same way, right? – Sphenogram^
is 2x slower, but the difference is greater! I've used this:console.time('^'); for(var i=0,x=0;i<1e6;i++)x+=13^15; console.timeEnd('^'); console.time('!='); for(var i=0,x=0;i<1e6;i++)x+=13!=15; console.timeEnd('!=');
. – Sphenogramx+=13^15;
withx+=!13^15;
(notice the!
). – Sphenogram1e6
times instead of1e5
times will discard that possibility. Otherwise, I would completely agree with you. – Sphenogram