note 104031 added to language.operators.bitwise

From: Date: Wed, 18 May 2011 13:31:52 +0000
Subject: note 104031 added to language.operators.bitwise
Groups: php.notes 
Request: Send a blank email to php-notes+get-179848@lists.php.net to get a copy of this message
A general comment in response to Josh: reconsider using pow() when a simple power of 2 is needed, especially in cases where this operation must be done many times. Bit-shift operations are much faster than resorting to chained multiplication or floating-point operations, which is what I assume the pow() function does. To benchmark the differences, run this program: <?php $tick = microtime(true); for ($i = 0; $i < 1000000; ++$i) { for ($j = 0; $j < 64; ++$j) { $k = pow(2, $j); } } $tock = microtime(true); print "Time using pow: " . ($tock - $tick) . " seconds\n"; $tick = microtime(true); for ($i = 0; $i < 1000000; ++$i) { for ($j = 0; $j < 64; ++$j) { $k = (1 << $j); } } $tock = microtime(true); print "Time using <<: " . ($tock - $tick) . " seconds\n"; ?> On my system, I find that the bit-shift operator is about 4 times faster than pow() when calculating powers of 2. ---- Server IP: 69.147.83.197 Probable Submitter: 129.55.200.20 ---- Manual Page -- http://www.php.net/manual/en/language.operators.bitwise.php Edit -- https://master.php.net/note/edit/104031 Del: integrated -- https://master.php.net/note/delete/104031/integrated Del: useless -- https://master.php.net/note/delete/104031/useless Del: bad code -- https://master.php.net/note/delete/104031/bad+code Del: spam -- https://master.php.net/note/delete/104031/spam Del: non-english -- https://master.php.net/note/delete/104031/non-english Del: in docs -- https://master.php.net/note/delete/104031/in+docs Del: other reasons-- https://master.php.net/note/delete/104031 Reject -- https://master.php.net/note/reject/104031 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#179848) next »