Wednesday, 27 June 2012

php code optimization tips

Wrap your string in single quotes (’) instead of double quotes (”) is faster because PHP searches for variables inside “…” and not in ‘…’, use this when you’re not using variables you need evaluating in your string.

If method is static, declare that method for once and reuse that method and achieve improvement in speed.

Echo is faster than print
echo and print are virtually (not technically) the same thing. The (pretty much only) difference between the two is that print will return the integer 1, whereas echo returns nothing. Keep in mind that neither is actually a function, but rather language constructs. echo allows you to pass multiple strings when using it as if it were a function (e.g., echo($var1, $var2, $var3)) 
echo can also be shorthanded by using the syntax <?= $var1; ?> (in place of <?php echo $var1; ?>).
Use loop limit calculation outside and same extra calculation
for($i=0; $i<$cnt*10; $++) replace with$count1 = $cnt*10;for($i=0; $i<$count1; $i++)
Unset the value of variable and get more freed space for faster performance
Use the unset($var); to unset the variable.
Avoid expensive require_once() and include_once() to for faster execution
_once() method do require to store log and has to check log every time for file requie/include.
Use fullpath because it takes less time in path resolving.

Possibly avoid regex by the use of strncasecmp, strpbrk or stripos.

str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4

If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.

It is better to use select statements than multi if, else if, statements.
if...else statement - use this statement if you want to execute a set of code when a condition is true and another if the condition is not true
elseif statement - is used with the if...else statement to execute a set of code if one of several condition are true
switch statement - is used if you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code.
Error suppression with @ is very slow.
@ is called error suppression symbol in php and used to tell php that it shouldn’t generate a warning (or a notice) as u know It’s perfectly correct to ignore that warning message. And overuse of that @ symbol can decrease your speed performance 

Turn on apache's mod_deflate
It is good to compress files on apache to reduce bandwidth usage and speed. This can be done by mod_deflate in apache 
In order to compress files using mod_deflate on Apache 2.x you first need to load the module, so you'll need to edit the Apache configuration. The exact location of the configuration file varies between each Linux/BSD distro, but it's often found at /etc/httpd/httpd.conf or /etc/apache2/httpd.conf, or /etc/httpd/conf/httpd.conf or /etc/apache2/conf/httpd.conf. If you are unsure of its location locate httpd.conf will usually send you in the right direction. 
So now that you've found the Apache config file, open it up in your favourite text editor as root or using sudo, and add this line: 
LoadModule deflate_module modules/ this section:
<Location />          AddOutputFilterByType DEFLATE text/html text/plain text/xml text/x-js text/css</Location> 
Always remember to close database connection after the use of that connection

If you are using prepared statement then remember to close stmt objects, and in select statement when you 
use store_result use free_result to free the memory
Use $stmt->free_result(); and 
$row['id'] is 7 times faster than $row[id], because if you don’t supply quotes it has to guess which index you meant, assuming you didn’t mean a constant.

Error messages are expensive try to reduce error message and warning messages

Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x++) The count() function gets called each time.
$cnt = count($array);
For($x=0; $x < $cnt; $x++)
Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in function.

Incrementing a global variable is 2 times slow than a local var.

Try to exchange calculation with cheaper instruction. Ex. Replace multiplication by cheaper instruction addition.
$z = $x*2;
$z = $x+$x;
Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable

Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

Try to use local variable rather than global variable. 
Little time is waste behind checking the global variable
Surrounding your string by ' instead of “ will make things interpret a little faster since php looks for variables inside ”..." but not inside '...' . Of course you can only do this when you don't need to have variables in the string.

A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
Means use html tags outside the php script code by breaking php scriptAvoid <?php echo “<br />” ?> and use simply <br />
Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.

Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request

When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.
if (strlen($foo) < 5) { echo "Foo is too short";}
if (!isset($foo{5})) { echo "Foo is too short"; }
Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length.

When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.

Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.

Do not implement every data structure as a class, arrays are useful, too

Don't split methods too much, think, which code you will really re-use

You can always split the code of a method later, when needed

Make use of the countless predefined functions

If you have very time consuming functions in your code, consider writing them as C extensions

Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview

mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%