note 97415 added to control-structures.while

From: Date: Mon, 19 Apr 2010 01:20:41 +0000
Subject: note 97415 added to control-structures.while
Groups: php.notes 
Request: Send a blank email to php-notes+get-168384@lists.php.net to get a copy of this message
I just discovered something interesting. I set up a series of loops as follows: #!/usr/bin/php <?php // loop with a boolean; logically, we'd expect this to be fastest $start = microtime(true); echo "Bool Start: $start\n"; $i = 0; while (true) if ($i++ > 100000000) break; $end = microtime(true); echo " End: $end Length: " . ($end - $start) . "\n"; // run the loop with a string instead, since 'a long string' == true $start = microtime(true); echo "String Start: $start\n"; $i = 0; while ('a long string') if ($i++ > 100000000) break; $end = microtime(true); echo " End: $end Length: " . ($end - $start) . "\n"; // and finish with an integer, since again 1234567890 == true $start = microtime(true); echo "Int Start: $start\n"; $i = 0; while (1234567890) if ($i++ > 100000000) break; $end = microtime(true); echo " End: $end Length: " . ($end - $start); ?> You'd expect the boolean to be fastest since there's no type conversion taking place, but this is the result: Bool Start: 1271638221.55 End: 1271638229.25 Length: 7.69345498085 String Start: 1271638229.25 End: 1271638236.23 Length: 6.98578810692 Int Start: 1271638236.23 End: 1271638243.86 Length: 7.62530088425 Using a string in the while loop is in fact significantly faster than the boolean or integer. Go figure, hey? This is useful when writing daemons in PHP with an infinite loop at their heart, such as the IRC bot I'm working on right now. (In order to avoid an infinite loop tying up all system resources, include sleep() or usleep() in there to slow things down a bit.) ---- Server IP: 69.147.83.197 Probable Submitter: 75.152.158.92 ---- Manual Page -- http://www.php.net/manual/en/control-structures.while.php Edit -- https://master.php.net/note/edit/97415 Del: integrated -- https://master.php.net/note/delete/97415/integrated Del: useless -- https://master.php.net/note/delete/97415/useless Del: bad code -- https://master.php.net/note/delete/97415/bad+code Del: spam -- https://master.php.net/note/delete/97415/spam Del: non-english -- https://master.php.net/note/delete/97415/non-english Del: in docs -- https://master.php.net/note/delete/97415/in+docs Del: other reasons-- https://master.php.net/note/delete/97415 Reject -- https://master.php.net/note/reject/97415 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#168384) next »