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

Testing String Variables

BulletThough various development books have their own opinion of using strlen(), empty(), and isset() (most say don't use strlen to validate strings because of performance considerations), I have always wondered as to their factual validity now that PHP is in its fifth incantation. This server unfortunately does not use the latest stable version of PHP, PHP5, but rather the tried and tested PHP4 which is still in wide use.

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
bulletstrlen()
  • Execution time: 4.94 ms
  • Average: 7.09 ms over 1128 trials
bulletempty()
  • Execution time: 2.92 ms
  • Average: 3.08 ms over 1128 trials
bulletisset()
  • Execution time: 2.34 ms
  • Average: 2.51 ms over 1128 trials
Results
Test Avg Execution Time Comparative Graph - (longer is slower, 100% is the fastest time)
strlen() 7.09 ms Performance Graph 282%
empty() 3.08 ms Performance Graph 123%
isset() 2.51 ms Performance Graph 100%

Discussion: Looks like the recommendation to avoid to the strlen() function was a wise one. isset() is definitely the fastest function, but for my purposes it is not as handy as empty(). isset() will return true even if a variable contains an empty string. Often, I am trying to validate user input and I'm not concerned if the variable is set, but rather that a non empty string value is present. To test variables for uses like this, I will use empty() and !empty().