php-tuneup

Top 5 Ways to Optimize You PHP code

PHP is undoubtedly one of the preferred development language for Web development. However, when the project is growing bigger and bigger, there is a real need to manage yout PHP codes so that it could run faster and efficiently. To optimize PHP codes, it require your indeep understanding the mechanism of those PHP built in function and coduct testing on it.

Here are 5 ways that you can modify to optimize you PHP code performance.

1) Loop

Loop are required by every program certain amount. And loop is considered as efficiency killer, if you have many nested loop as one loop will required to run ‘n’ times and if you have 1 nested loop, this means your program will have to run n2 times. However, today we can going talk about this. As you know, there are many ways to define a loop in PHP. But do you know which one is the best way to loop you data???

Compare the performance between for for() loop, foreach and while() loop:

A test conducted on foreach, while() loop and for() loop to run same function to loop a hash array? Given is a Hash array with 100 elements, 24byte key and 10k data per entry.

foreach loop

<?php// Initial Configuration
 global $aHash;
 $i   = 0;
$tmp = '';while($i < 10000) {
 $tmp .= 'a';
 ++$i;
 }

$aHash = array_fill(100000000000000000000000, 100, $tmp);
 unset($i, $tmp);

// Test Source
 function Test1_1() {
 global $aHash;    /* The Test */
 $t = microtime(true);
 reset($aHash);
 foreach($aHash as $val);

return (microtime(true) - $t);
 }
 // Variable Clean-up
 function Test1_End() {
 global $aHash;
 unset($aHash);
 }

?>

while() loop

<?php// Initial Configuration
 global $aHash;
 $i   = 0;
$tmp = '';while($i < 10000) {
 $tmp .= 'a';
 ++$i;
 }

$aHash = array_fill(100000000000000000000000, 100, $tmp);
 unset($i, $tmp);

// Test Source
 function Test1_2() {
 global $aHash;    /* The Test */
 $t = microtime(true);
 reset($aHash);
 while(list(,$val) = each($aHash));

return (microtime(true) - $t);
 }
 // Variable Clean-up
 function Test1_End() {
 global $aHash;
 unset($aHash);
 }

?>

for() loop

<?php// Initial Configuration
 global $aHash;
 $i   = 0;
$tmp = '';while($i < 10000) {
 $tmp .= 'a';
 ++$i;
 }

$aHash = array_fill(100000000000000000000000, 100, $tmp);
 unset($i, $tmp);
 // Test Source
 function Test1_3() {
 global $aHash;    /* The Test */
 $t = microtime(true);
 reset($aHash);
 foreach($aHash as $key => $val);

return (microtime(true) - $t);
 }
 // Variable Clean-up
 function Test1_End() {
 global $aHash;
 unset($aHash);
 }

?>

Results:

  • Total execution time of foreach() loop is 8 microseconds
  • Total time of while() loop is 58 microseconds
  • Total time of for() loop is 11 microseconds

In this test, we found that foreach loop is the fastest one. It is substantially faster than while() loop and slightly faster than for() loop. However, in some suitation, we may want to use for() loop. How should we optimize the performance of for() loop as well??

Optimize performance of for() loop

To optimize for() loop performance, the number of maximum loop should be pre-calculated outside the for() loop.

With per-calculated max loop

<?php// Initial Configuration
 global $x;
 $i   = 0;
$tmp = '';while($i < 10000) {
 $tmp .= 'a';
 ++$i;
 }

$x = array_fill(5, 1000, $tmp);
 unset($i, $tmp);
 // Test Source
 function Test3_1() {
 global $x;    /* The Test */
 $t = microtime(true);
 $size = count($x);
 for ($i=0; $i<$size; $i++);

return (microtime(true) - $t);
 }
 // Variable Clean-up
 function Test3_End() {
 global $x;
 unset($x);
 }

?>

Without per-calculated max loop

<?php// Initial Configuration
 global $x;
 $i   = 0;
$tmp = '';while($i < 10000) {
 $tmp .= 'a';
 ++$i;
 }

$x = array_fill(5, 1000, $tmp);
 unset($i, $tmp);

// Test Source
 function Test3_2() {
 global $x;    /* The Test */
 $t = microtime(true);
 for ($i=0; $i<count($x); $i++);

return (microtime(true) - $t);
 }
 // Variable Clean-up
 function Test3_End() {
 global $x;
 unset($x);
 }

?>

The example above shows two different ways of writing a for loop. The different between these two is that the second one do not run count operation n times while the fist one did. And the second one is much much faster than the first one. The time to complete first one is 133 microsecond and the time to complete second one is 59750 microsecond. Hence, with pre-calculated max number of loop could significanly increase the performance.

2) Pre-increment vs Post-increment

There are many ways to increment a certain value.

$i++;
 $++i
 $i+=1;
 $i = $i + 1;

Out of the above, which one is the most efficient?? In PHP, pre-increment seems like better than other. And it is around 10% better than  post-increment.There isn’t any benchmark done for PHP but i found one on C++ which should be quite the same. Well, without a proper benchmark on this, i can’t really confirm this. Furthermore, it really doesn’t makes a big differences towards normal programmers but may affect those who are working towards micro optimization. Nonetheless, many people do suggest pre over post increment in term of optimization.

3) Dot Vs Commas Concatenation

When you need to concatenate between two string/variable, you use dot or commas?

$a = '10 PHP programming ';
 $b = 'Improvement Tips';
 #10 PHP Programming Improvement Tips
 echo $a.$b;</div>
<div>$a = '10 PHP programming ';
 $b = 'Improvement Tips';
 #10 PHP Programming Improvement Tips
 echo $a,$b;

Personally, I use dot instead of commas. By conducting a test, we can concluded that dot is more efficiency that commas.

echo string with comma

<?php// Test Source
 function Test11_6() {
global $answer;/* The Test */
 ob_start();
 $t = microtime(true);
 while($i < 1000) {        echo 'aaaaaaa','aaaaaaa','aaaaaaa','aaaaaaa';

++$i;
 }

$tmp = microtime(true) - $t;
 ob_end_clean();    return $tmp;
 }

// Variable Clean-up
 function Test11_End() {
 global $answer;
 unset($answer);
 }?>

echo string with dot

<?php// Test Source
 function Test11_7() {
global $answer;/* The Test */
 ob_start();
 $t = microtime(true);

while($i < 1000) {        echo 'aaaaaaa'.'aaaaaaa'.'aaaaaaa'.'aaaaaaa';

++$i;
 }

$tmp = microtime(true) - $t;
 ob_end_clean();    return $tmp;
 }

// Variable Clean-up
 function Test11_End() {
 global $answer;
 unset($answer);
 }?>

The result shows that total time to complie echo with dot is 103 microsecond and echo with comma is 174 microsecond. Here we can confirm that concatenate strings / variables with dot is much efficient.

4) String Manipulation – string replace

PHP have three function for string search function, which are str_replace ,preg_replace & ereg_replace. Amount three function which one is the fastest. According to this testing, preg_replace runs 86.99% faster than  str_replace function call.

5) String Manipulation – split string

When you want to split string, you would use explode or preg_split. However, do you know which is faster?? A tested conducted, explode() is the fastest by around 15%. The reason is that preg_split() supports regular express and this makes it slower than those that does’t support it.

$GLOBALS['dummy2'] = preg_split('~\r\n|\r|\n~', $GLOBALS['dummy']);</div>
Finish in 1.1345 seconds.
<div>$GLOBALS['dummy2'] = explode("\n", str_replace(array("\r\n", "\r"), "\n", $GLOBALS['dummy']));</div>
Finish in 0.154 seconds.
To Conclude

I believe that many of you have see all of these information before. However, it is always good to refresh yourself. And apply all the tips on above when you code.

Related Posts


7 thoughts on “Top 5 Ways to Optimize You PHP code

  1. kore dizileri izle

    Greetings thanks for great submit i used to be seeking for this challenge last 2 days. I will look for subsequent precious posts. Have pleasurable admin.

    Reply
  2. Paul Troiani

    I just want to tell you that I’m all new to weblog and really savored this blog. Most likely I’m likely to bookmark your site . You really come with outstanding articles and reviews. Appreciate it for revealing your website.

    Reply
  3. Lucy

    hey admin thanks for excellent and effortless understandable submit i cherished your web site website seriously much bookmarked also

    Reply
  4. air max 1

    Hello I like your blog. Do you need to visitor publish on my very own at some point? If so please inform me by means of e-mail or perhaps reply to this kind of opinion since We enrolled in notifications and will understand should you choose.

    Reply
  5. Jasmine Melander

    I simply want to tell you that I’m beginner to blogs and truly loved this web-site. Probably I’m likely to bookmark your blog . You amazingly come with impressive well written articles. With thanks for revealing your blog.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *


*