Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shift bits vs multiply in PHP

Tags:

I have the following code:

<?php $start = 1;  $timestart = microtime(1); for ($i = 0; $i < 1000000; $i++) {     $result1 = $start * 4; } echo "\n"; echo microtime(1) - $timestart; echo "\n";  $timestart = microtime(1); for ($i = 0; $i < 1000000; $i++) {     $result2 = $start << 2; } echo "\n"; echo microtime(1) - $timestart; echo "\n"; 

This outputs:

0.14027094841003  0.12061500549316 

I found on the Internet a Google interview question (which I wanted to apply for a developer, but I realize I can't), and one of the questions asked what the fastest way was to multiply a number. My first thought was to use the * sign, so I tested it.

My question is, why is shifting bits faster than multiplication?

like image 382
aki Avatar asked Nov 24 '11 02:11

aki


1 Answers

Because bit shifting is something the computer does all the time in hardware, it's a no-brainer for the CPU. Multiplying arbitrary numbers is something more difficult, because it can't necessarily be done using simple bit shifting but requires actual work. Multiplying a small integer by 4 happens to be an operation that's identical to a left-shift by 2. But even if the compiler/runtime/CPU optimizes this operation down to a bit shift, some code first needs to recognize that it can be optimized this way, which is more work than a simple bit shift itself.

Either way, it's simply more work because the two operations do entirely different things, even if the outcome of certain operations is the same.

like image 102
deceze Avatar answered Nov 17 '22 21:11

deceze