Go Back   TechArena Community > ARENA > Guides & Tutorials
Become a Member!
Forgot your username/password?
Register Tags Active Topics RSS Search Mark Forums Read

Sponsored Links



Some tricks of PHP code optimization

Guides & Tutorials


Reply
 
Thread Tools Search this Thread
  #1  
Old 04-01-2011
Member
 
Join Date: Sep 2010
Posts: 66
Some tricks of PHP code optimization
  

PHP is a language for programming interpreted, meaning that the text file containing the PHP code is parsed and then processed directly (not compiled code). We'll see how to improve the performance of your PHP scripts to maximize performance. The various optimization techniques that we will see here will help you:
  • Generate your pages faster for the visitor
  • To save server resources
  • To receive more visitors at the same time on your site
  • Encode more cleanly, since optimization rhyme often (not always) with clarity and cleanliness.
Following the various remarks more or less grounded than I have read on the net, I want to say that the beginning of this article will not make you win a huge generation time if your page is poorly coded and that s' acts of micro-optimizations, it thus replaced by no means an algorithm optimized for this any page of your site. Prefer thus improving your algorithms before eventually optimize the few phrases that might cause you to lose a few thousands of seconds.

We'll start by optimizing the few milliseconds you might lose the use of office less effective than others. All benchs that follow were performed with version 5.2.4 of PHP, the latest as I write these lines. They consist in the execution of a loop containing a number n of iterations (this number n is specified in front of each bench because the differences are sometimes so small that they require a larger number of iterations so that the they can be seen). Within this loop is the code for which we test performance. At the end of the script, we count the number of seconds required to run and therefore we compare the different codes between them. The benchs were executed five times to take the average generation time and reduce errors. Attack!!

Reply With Quote
  #2  
Old 04-01-2011
Member
 
Join Date: Sep 2010
Posts: 66
Re: Some tricks of PHP code optimization

The single and double quotes:

Let's start with a classic PHP namely single and double quotes (quotation marks). They derive their main difference is that everything is within single quotes is not interpreted, contrary to what is inside double quotes. In practice the following code does exactly the same thing:

PHP Code:
<? Php 
echo 'Here is a test string'
?> 

<? Php 
echo "This is a test string"
?>
Cons by the following code will give two different results:
Version 1:
PHP Code:
<? Php 
Myvar 'hello world'
echo 
"Variable Value: $ myvar '; 
?>
Version 2:
PHP Code:
<? Php 
Myvar 'hello world'
echo 
"Variable Value: $ myvar"
?>
When you use the second version of this example, you see that the string $ myvar is replaced by its value, unlike what happens in the first version of this example. Now, replace its value by $ myvar requires additional time for PHP because it must not only find the exact name of the variable but then substitute its value. That is why it is faster to use version 1. Although you may say, but what if you want to display the contents of a variable? well, we will be able to use concatenation. Resume our slow code and optimize it:
Version 1:
PHP Code:
<? Php 
Myvar 'hello world'
echo 
"Variable Value: $ myvar"
?>
Version 2:
PHP Code:
<? Php 
Myvar 'hello world'
echo 
'Variable Value'. $ myvar
?>
Version 3:
PHP Code:
<? Php 
Myvar 'hello world'
print 
'Variable Value'. $ myvar
?>
We can also (as of version 3) use the print function. It has an echo difference, however: it always returns 1, so that you can use it in conditions or otherwise. In practice, it is supposed to be slower.
Reply With Quote
  #3  
Old 04-01-2011
Member
 
Join Date: Sep 2010
Posts: 66
Re: Some tricks of PHP code optimization

It is noted here that there is no average difference between print and echo (attention, however, I found that print could be faster than echo, but it's usually the opposite. The average has smoothed results) . You can (and only echo) replace the item with a comma concatenation. This can be faster (about 200 iterations I did not get enough differences, however). This is because it is often faster to concatenate a piece of string and throw everything in the same buffer as close and reopen the buffer needed each time you use echo. Here is what it is:
Concatenation with the point:
PHP Code:
<? Php 
Myvar 'hello world'
echo 
'Variable Value'. $ myvar
?>
"Concatenation" with the comma:
PHP Code:
<? Php 
Myvar 'hello world'
echo 
"Variable Value: ', $ myvar; 
?>
After this brief passage about the print function and structure of language echo let's tackle the different ways of coding. Let's start with the declaration (and initialization) of variables. Unlike PHP4 when I got quicker results for version 1, this is version 2 (more logical) who wins by a short head. Turning now to the conditions. There are three ways to make conditions in PHP:
  1. The condition if / else
  2. The switch statement
  3. The ternary operator
The three can do the same thing with varying syntax. See three examples that are absolutely the same but written differently:
Version 1:
PHP Code:
<? Php 
Variable 1
0

if ($ 
variable === 1

+ +; 

elseif ($ 
variable === 2

2

else 

3

?>
Version 2:
PHP Code:
<? Php 
Variable 1
0

switch ($ 
variable

case 
1
+ +; 
break; 
Box 2
2
break; 
default: 
3
break; 

?>
Version 3:
PHP Code:
<? Php 
Variable 1
0

($ 
Variable === 1)? $ + +: (($ variable === 2)? $ 2: $ 3); 
?>
The first version uses the classical operator in PHP, ie the condition if / else. The second version uses a switch while the latter uses what is called the ternary operator. The three options have advantages and disadvantages of different views including maintenance, but we are only here to judge their performance.
Reply With Quote
  #4  
Old 04-01-2011
Member
 
Join Date: Sep 2010
Posts: 66
Re: Some tricks of PHP code optimization

Turning now to the loops, and more specifically to the use of the count () function in a loop. Many of you put a count () in a loop so that the loop stops once to increment the variable exceeds the value returned by count (). However, in general, you work on an array of fixed size, ie count () will return to the same value each time. When you make a loop, the value of count () is recalculated for nothing! Here are two codes which I mean:

Version 1:

PHP Code:
<? Php 
0
$ Array = array (
'test''hop'); 
count ($ array); 

for ($ 
0; $ <$ n, $ + +) 

+ +; 

?>
Version 2:

PHP Code:
<? Php 
0
$ Array = array (
'test''hop'); 

for ($ 
0; $ <count ($ array); $ + +) 

+ +; 

?>
Place a count () in a loop here is twice as slow! Preference will be given so the first solution. In the same kind of thing, let's see the impact that may have to use a for loop or while loop:

Version 1:

PHP Code:
<? Php 
0
while ($ 
<50

+ +; 

?>
Version 2:

PHP Code:
<? Php 
    
for ($ 0; $ <50; $ + +) 



?>
There are many ways in PHP to replace a portion of a string with another value. Here are the two main functions used for this:
  • preg_replace ()
  • str_replace ()
Remember that it is faster to use str_replace () and preg_replace (), for str_replace () takes a string parameter fixed, contrary to preg_replace () that uses regular expressions . Of course if you want to replace a string in a very specific condition, the function str_replace () is generally not powerful enough and you will need to use preg_replace ().
Reply With Quote
  #5  
Old 04-01-2011
Member
 
Join Date: Sep 2010
Posts: 66
Re: Some tricks of PHP code optimization

Prefer the use of the function foreach () instead of using the couple while (list () = each ()). We'll prove it to fill an array of 1000 random values, then we'll walk 200 times this picture of two ways that I just mentioned. Here are the codes used:

Version 1:

PHP Code:
<? Php 
0
foreach ($ array AS $ 
key => $ value

+ +; 

?>
Version 2:

PHP Code:
<? Php 
0
while (list ($ 
key, $ value) = each ($ array)) 

+ +; 

?>
After all these micro optimizations, we'll talk about other ways to optimize your PHP scripts in order to improve this time consistently performance. These changes are more oriented algorithms or databases. In PHP, there are many solutions to simplify the task of designers and developers. They can not only facilitate the process, but also accelerate the generation time of your scripts if properly used. We can talk about particular engine templates, you can find a version designed by me here (PHP5): PHP template engine . Through the use of such sources, you will have mostly a "hidden" mode. Hide information is saved to a file or a database in order to reduce the processing needed to display the data next time. For example, when you view a list of your news, you know it will not update every minute, there is no need to reapply to the base while the news content and make top salaries at each Once a visitor clicks on the page. You can retrieve once and for all that list, the cache (in a text file for example) and then reuse it instead of using the database. This kind of trick can easily fall by 50% the generation time of your pages and consume fewer resources CPU (sometimes in defiance of the amount of RAM consumed). These scripts and optimization methods are especially important when you have a website visited a minimum. If you have ten visitors daily and that your treatments are not too heavy, it is unnecessary to implement a caching system, but who can do more can do less as they say.
Reply With Quote
Reply

  TechArena Community > ARENA > Guides & Tutorials
Tags: , , , , , ,



Thread Tools Search this Thread
Search this Thread:

Advanced Search


Similar Threads for: "Some tricks of PHP code optimization"
Thread Thread Starter Forum Replies Last Post
Better code with onsite optimization Inigo Technology & Internet 6 23-02-2011 03:02 PM
Optimization in MySQL Calan Software Development 4 21-12-2010 12:35 AM
Best PC Optimization Tools Maq.H Reviews 2 21-01-2010 12:57 AM
SSE Optimization on AMD CPU Tobius Software Development 2 14-01-2009 06:54 PM
System Optimization Tricks ravi_mishra Tips & Tweaks 22 20-05-2006 12:23 PM


All times are GMT +5.5. The time now is 05:52 PM.