Testing booleans is a common code occurance in programs, and I have been trying to be a good programmer and use $var===true (=== means exactly equal, == means equivalent.) However, I also worry about performance, and I suspect that using the exactly equal to comparison is slowing down scripts where I'm doing many, many comparisons.
Test Environment: Linux, Apache, PHP 5.2.17.
Test Setup: Code constructs listed below. For loops used to have enough iterations to make the script execution time calculatable. Each test was run 3000 times to get the average.
Comparisons
Using ($var)
$var=true;
for($i=0; $i<1000; $i++)
{
if($var)
{
//do something
}
}
Using $var==true
$var=true;
for($i=0; $i<1000; $i++)
{
if($var==true)
{
//do something
}
}
Using $var===true
$var=true;
for($i=0; $i<1000; $i++)
{
if($var===true)
{
//do something
}
}
| Results | ||
|---|---|---|
| Test | Avg Execution Time | Comparative Graph - (longer is slower, 100% is the fastest time) |
| ($var) | 0.34 ms | |
| $var==true | 0.46 ms | |
| $var===true | 0.37 ms | |
Discussion: This was surprising to me, and somewhat defies explanation given that if($var) and if($var==true) should be equivalent expressions in the back end of php. It's too bad too that trying to be clear with your code has performance implications. I think if($var==true) is far more clear than if($var) because it also implies that we are dealing with boolean typed variables rather then possibly numbers or strings. Of course if($var===true) is even more clear and indeed faster, so I will continue to use this expression whereever it is applicable.