note 93624 deleted from types.comparisons by danbrown

From: Date: Fri, 18 Sep 2009 19:54:16 +0000
Subject: note 93624 deleted from types.comparisons by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-160848@lists.php.net to get a copy of this message
Note Submitter: Michael ---- The following two conditional statements are identical: <?php if ($foo) { ... } if (!empty($foo)) { ... } ?> ...as are the following: <?php if (!$foo) { ... } if (empty($foo)) { ... } ?> However, checking to see if a variable is empty is (very slightly) quicker than checking to see if a variable is false, and checking to see if a variable is true is (very slightly) quicker than checking to see if a variable is not empty: <?php // Create the array $awesome = array(); // Populate the array with FALSE for ($i = 0; $i <= 1000000; $i++) { $awesome[$i] = false; } // Check to see if the value is true $one = microtime(true); foreach ($awesome as $foo) { if ($foo) { return true; } } $two = microtime(true); $bar1 = $two - $one; // Check to see if the value is not empty $one = microtime(true); foreach ($awesome as $foo) { if (!empty($foo)) { return true; } } $two = microtime(true); $bar2 = $two - $one; // Populate the array with TRUE for ($i = 0; $i <= 1000000; $i++) { $awesome[$i] = true; } // Check to see if the value is false $one = microtime(true); foreach ($awesome as $foo) { if (!$foo) { return true; } } $two = microtime(true); $bar3 = $two - $one; // Check to see if the value is empty $one = microtime(true); foreach ($awesome as $foo) { if (empty($foo)) { return true; } } $two = microtime(true); $bar4 = $two - $one; print_r($bar1); // 0.0960810184478 (TRUE) print_r($bar2); // 0.1212460994720 (NOT EMPTY) print_r($bar3); // 0.1063888072967 (FALSE) print_r($bar4); // 0.1030158996582 (EMPTY) ?>

« previous php.notes (#160848) next »