PHP & Web Development :: PHP Performance + Benchmarking :: Testing Boolean Variables

Testing Boolean Variables

BulletTesting 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 4.3.11 with PHP loaded using FastCGI. Zend Optimizer 2.5.7 installed. What's Zend Optimizer?

Test Setup: Code constructs listed below. For loops used to have enough iterations to make the script execution time calculatable.

Refresh the page to execute a new trial!

Comparisons
Bullet($var)
  • Execution time: 0.37 ms
  • Average: 0.29 ms over 965 trials
Bullet$var==true
  • Execution time: 1.07 ms
  • Average: 0.53 ms over 965 trials
Bullet$var===true
  • Execution time: 0.42 ms
  • Average: 0.46 ms over 965 trials
Results
Test Avg Execution Time Comparative Graph - (longer is slower, 100% is the fastest time)
($var) 0.29 ms Performance Graph 100%
$var==true 0.53 ms Performance Graph 183%
$var===true 0.46 ms Performance Graph 159%

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.