note 106027 deleted from function.abs by hholzgra

From: Date: Sun, 15 Apr 2012 19:31:57 +0000
Subject: note 106027 deleted from function.abs by hholzgra
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-187151@lists.php.net to get a copy of this message
Note Submitter: Tig ---- In trying to workout the fastest way to return a number equal to or great than 0 from any input, with < 0 turned positive as well, these are my results and how I tested: Fastest method: $x = floor($input); $x = ($x < 0) ? ($x * -1) : $x; With ?n=987 passed 1) Result [987]: 0.020493030548096 sec. 2) Result [987]: 0.072222948074341 sec. 3) Result [987]: 0.23027300834656 sec. With ?n=-821 1) Result [821]: 0.023087024688721 sec. 2) Result [821]: 0.073657035827637 sec. 3) Result [821]: 0.24681091308594 sec. With ?n=foo 1) Result [0]: 0.020076990127563 sec. 2) Result [0]: 0.065827131271362 sec. 3) Result [0]: 0.17472290992737 sec. Also works with nothing passed. The test page code: <?php // test 1 $start = microtime(true); $x = floor($_GET['n']); $i = 0; do { $tmp = ($x < 0) ? ($x * -1) : $x; } while($i++ < 100000); $end = microtime(true); echo '1) Result ['.$tmp.']: '.($end - $start).' sec.<br />'; // test 2 $start = microtime(true); $x = $_GET['n']; $i = 0; do { $tmp = abs($x); } while($i++ < 100000); $end = microtime(true); echo '2) Result ['.$tmp.']: '.($end - $start).' sec.<br />'; // test 3 $start = microtime(true); $x = floor($_GET['n']); $i = 0; do { $tmp = str_replace('-','',$x); } while($i++ < 100000); $end = microtime(true); echo '3) Result ['.$tmp.']: '.($end - $start).' sec.<br />'; ?>

« previous php.notes (#187151) next »