Posts

PHP Profiling – Performance Optimization Techniques

Performance optimization can measure the performance of our server side scripts using several tools in different environments. Let’s discuss a few coding styles and a few PHP optimization tricks that ensure better performance of speed without caching.

Performance optimization can measure the performance of our server side scripts using several tools in different environments, especially XDebug in development. In this article, we are going to concentrate on coding techniques, and use XDebug to measure the performance of different scriptlets. We ran the codes several times and took the average execution time to create our benchmark. Let’s discuss a few coding styles and their impact on the performance.

1. Using the Latest Version of PHP
With each major release of the language, the community provides considerable improvement in terms of speed.

php-bench-comparison1

Please note that PHP 7 is yet not recommended for the production environment, however, it claims to be much faster than its predecessors.

2. Double Quotes (“) and Single quotes (‘)
This can be a debate among several developers as which one is the faster. Usually, we all know that double quotes (“) checks for the presence of variables and adds a little bit of overhead in case of strict strings. But it’s not true for normal assignments, loops with fewer iterations or concatenation or interpolation of smaller bytes as it never shows any difference at all. We have tested using the following script.

double-quote-vs-single-quote-test-865x1024

However, you can observe noticeable difference for larger strings or huge iterations where single quotes run faster than double quotes. Definitely, such micro-optimizations are not required, still, it’s a good programming practice to use single and double quotes sensibly wherever the need be, from a performance point of view.

3. Avoiding Relative Path In File Inclusion
As the system tries to resolve the relative path to an absolute path before processing, so we can save a step by providing an absolute path. Best practices include defining and declaring a WEB_ROOT and then use it globally wherever required.

4. Releasing all Resources
Unsetting large arrays, closing a file handler, closing a database connection or a curl request to any other server through an API are amongst the various other things that developers usually overlook. As a result, more memory is occupied in maintaining the resources. We know that there is a garbage collector to do the tasks for us, but then we do not know when it would be called..! It is always better to close a resource after it’s opened and our work is done. We can also use destructors in our classes as we know when the program controller exits a class. If a destructor is present, then it would automatically call the garbage collector.

5. Avoid Unnecessary Use of Global Variables
Accessing a global variable is twice as costly as accessing a local variable, so if a global is declared and not used, or could have been declared as local, it adds up to a considerable amount of overhead.

6. Never Use Count or Any Other methods in The Condition Section of a Loop
For example: for ($x = 0; $x < count($array); $x++), in this statement the count function is called each time the loop iterates and it does the same thing over and over again. Instead if we declare a variable say $count = count($array); and then for ($x = 0; $x < $count; $x++), we can save processing time.

7. Using ISSET
Instead of using count(), strlen(), sizeof(), it is better as well as safer to use isset() to compare the value returned with a specific number. Suppose we have a condition like (strlen($foo) < 50) we can do it like (!isset($foo{50})) and see the performance change.

8. Using more of Static Methods/Properties
Static methods/ properties are generally faster than non-static ones. However, if an object is pre-initialized and then a non-static method/property is called repeatedly on the same object, non-static is faster.

Non-static methods skip a step of object initialization making it faster by 20% on an average.

With an exception of PHP5.3 where nonstatic methods are faster, but that was due to because of the bug that was present in PHP 5.3 when they introduced late static bindings. The bug was fixed in later versions of PHP.

9. foreach > for > while
According to our benchmarks, the foreach loop is much faster than the for loop and for loop is faster than the while loop.

php-read-loop

10. Pre and Post Increments
This is again a widely debated topic. It behaves differently in different languages and depends upon the environment. Post-incrementation in PHP has been documented as storing a temporary variable which attributes to this 10% overhead vs. pre-incrementation.

++$i is pre-incrementation, $i is incremented and the new value is returned

$i++ is post-incrementation, the value of $i copied to an internal temporary variable, $i is incremented and the internal copy of the old value of $i is returned.

The difference measured by us is not much, so it’s being recommended in this case to use it according to the need without worrying about the microscopic difference.

11. Echo, print, comma, printf, and sprintf
Echo is a language construct whereas print is a function, so without testing we can say echo is faster than print, most of the developers we have seen use echo over print, and so this should not be a cause of worry, however, we have noted a considerable and noticeable difference when strings are concatenated using a comma and not the period operator.

For example: echo $a, $b, $c; is faster than echo $a . $b . $c;, but echo $a . $b . $c; is faster than print $a . $b . $c.

Like C/C++ in PHP, we have printf and sprintf functions, which are least used in PHP scripts. Let us see one such example where we can use them.

$query = sprintf( “SELECT * FROM users WHERE username=’%s’ AND password=’%s'”, $_user, $_password );

Using sprintf is 10 times faster than using variables within double quotes in string formatting. There is a little difference between sprintf and printf. printf outputs the string, whereas sprintf stores the string in a variable.

12. Using Identical Operator (===) Anywhere Possible
The equality operator == typecasts, or converts the data type temporarily to see if it’s equal to the other operand whereas === ( identity operator ) doesn’t need to do any converting whatsoever and thus, it does lesser work, making it comparatively fast.

There are plenty of areas where we can improve on this, which we will discuss more of in our subsequent articles. Stay tuned for our upcoming posts.