Quick tips for improving PHP Performance

Recently I was studying about improving the performance of our PHP code. While surfing through the web I came out with some interesting tips about improving the performance of your PHP code. All the tips have been verified by renowned authors(including Google) and there is nearly no doubt regarding their authenticity. I want to share these tips with my readers. So here we go…



1. ‘echo’ is much faster than print. So always try echo something rather than printing it.

	/*This is faster*/
echo 'This is echoed text';

/*This is slower*/
print 'This is printed text';

2. Always use the stacked form of echo instead of using concatenation. e.g

	/*Faster form of echo*/
echo 'This is stacked form of ', $variable;

/*Slower form of echo*/
echo 'This is regular form of ' . $variable;

3. Use of single quotes rather than double quotes with echo can improve the performance of your code because compiler will not search for the variables inside the single quotes but in double quotes it will perform a search for possible variables.

	/*Faster form of echo*/
echo 'This is single quoted string.';

/*Slower form of echo*/
echo "This is double quoted $string.";

4. Use pre-increments where possible instead of post-increments. Pre-incrementing is faster than post-increments.

	/*Slower form of iteration*/
for ( $i=0; $i < 1000; $i++ ) {
echo 'Loop ',$i;
}

/*Faster form of iteration*/
for ( $i=0; $i < 1000; ++$i ) {
echo 'Loop ',$i;
}

5. Never use calculations as counters in an iteration.

	/*Slower form of iteration*/
for ( $i=0; $i < count($arr); $i++ ) {
echo 'Loop ',$i;
}

/*Faster form of iteration*/
$counter = count($arr);

for ( $i=0; $i < $counter; $i++ ) {
echo 'Loop ',$i;
}

6. Always unset the variable after using those. It may save some of your resources on the server.

	$counter = count($arr);

for ( $i=0; $i < $counter; $i++ ) {
$value = $arr[$i];

foo( $value );//call any function

unset($value);//unset the variable after using it.
}

7. Always initialize your variables before using those. It can sometimes prove beneficial in terms of performance.

	$counter = count($arr);

$value = '';//initialize the variable before using it

for ( $i=0; $i < $counter; $i++ ) {
$value = $arr[$i];

foo( $value );//call any function

unset($value);//unset the variable after using it.
}

8. Always close the database connections after you are done with the queries.

	mysql_connect('localhost', 'root', 'secret123');

mysql_select_db('test_db');

//write database queries here

mysql_close();//close the connection at the end

9. Avoid strlen() to check the length of a string. Checking the desired index in the string can also work.

	/*Slower form*/
if ( strlen($str) > 100 ) {
echo 'You have crossed the limits';
}

/*Faster form*/
if ( $str[100] ) {
echo 'You have crossed the limits';
}

10. Use include() and require() instead of include_once() and require_once(). There’s a lot of work involved in checking to see if a file has already been included. Sometimes it’s necessary, but you should default to include() and require() in most situations.

11. Use full file paths on include/require statements. Normalizing a relative file path can be expensive; giving PHP the absolute path (or even “./file.inc”) avoids the extra step.

12. Don’t copy variables for no reason. Sometimes PHP novices attempt to make their code “cleaner” by copying predefined variables to variables with shorter names before working with them. What this actually results in is doubled memory consumption (when the variable is altered), and therefore, slow scripts. In the following example, if a user had inserted 512KB worth of characters into a textarea field. This implementation would result in nearly 1MB of memory being used.

	/*Slower form*/
$description = strip_tags($_POST['description']);
echo $description;

/*Faster form*/
echo strip_tags($_POST['description']);

13. Avoid doing SQL queries within a loop. A common mistake is placing a SQL query inside of a loop. This results in multiple round trips to the database, and significantly slower scripts. In the example below, you can change the loop to build a single SQL query and insert all of your users at once.

	foreach ($userList as $user) {
$query = 'INSERT INTO users (first_name,last_name) VALUES("' . $user['first_name'] . '", "' . $user['last_name'] . '")';
mysql_query($query);
}

Produces:

	INSERT INTO users (first_name,last_name) VALUES("John", "Doe")

Instead of using a loop, you can combine the data into a single database query.

	$userData = array();
foreach ($userList as $user) {
$userData[] = '("' . $user['first_name'] . '", "' . $user['last_name'] . '")';
}
$query = 'INSERT INTO users (first_name,last_name) VALUES' . implode(',', $userData);
mysql_query($query);

Produces:

	INSERT INTO users (first_name,last_name) VALUES("John", "Doe"),("Jane", "Doe")...

14. Avoid OOP whenever you can. You should use OOP concepts only when these are really required. Study the situation you are working in. If you can do the things without OOP concepts, do it without hesitation. Using OOP for smaller tasks will always increase overhead rather than improving the performance. So the core concepts can help in most of the situations.’

15. Always strive for caching. Each time your request is processed by the server, the server has to reproduce the similar content repetitively. This wastes a lot of server resources just for nothing useful. So try to implement templating systems like ‘Smarty’. It will always fasten your web application.

16. Using in built functions of PHP is many times faster than using custom build functions. So search the PHP manual thoroughly before writing your own function. Nearly every type of function is available in PHP.

Written by Arvind Bhardwaj

Arvind is a certified Magento 2 expert with more than 10 years of industry-wide experience.

Website: http://www.webspeaks.in/

3 thoughts on “Quick tips for improving PHP Performance

Comments are closed.