note 93624 added to types.comparisons
| From: | Michael at osu1 dot php dot net | Date: | Fri, 18 Sep 2009 19:47:22 +0000 |
| Subject: | note 93624 added to types.comparisons | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-160843@lists.php.net to get a copy of this message | ||
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)
?>
----
Server IP: 208.69.120.35
Probable Submitter: 90.221.195.184
----
Manual Page -- http://www.php.net/manual/en/types.comparisons.php
Edit -- https://master.php.net/note/edit/93624
Del: integrated -- https://master.php.net/note/delete/93624/integrated
Del: useless -- https://master.php.net/note/delete/93624/useless
Del: bad code -- https://master.php.net/note/delete/93624/bad+code
Del: spam -- https://master.php.net/note/delete/93624/spam
Del: non-english -- https://master.php.net/note/delete/93624/non-english
Del: in docs -- https://master.php.net/note/delete/93624/in+docs
Del: other reasons-- https://master.php.net/note/delete/93624
Reject -- https://master.php.net/note/reject/93624
Search -- https://master.php.net/manage/user-notes.php