Posted by: uttamkumar | July 9, 2008

PHP Optimization tips.

Art to tune a system to perform more  efficiently.
Improving Speed
Using less resources
Less memory uses     [In computing]
Disk Space             [In computing]
Bandwidth             [In computing]

When to Optimize code
After UI, since in the process of optimization UI can be screwed up.

Here is a good example to explain code optimization.Suppose I need to calculate sum of the numbers from 1-25.A normal code can be as follows.

int i, sum=0,N=25;
for (i = 1; i <= N; i++)‏
sum += i;
printf (“sum: %d\n”, sum);

But if you think wisely you can optimized this code.Here is the optimized code.

int sum = (N * (N+1)) / 2;
printf (“sum: %d\n”, sum);

So overall idea to present this exercise is let you know that several time code can be optimized by applying formula  and logic.I prefer  to plan  and build logic before actually  you start the code.Try for  2-3  different-2 logic  and  implement  the best one.Here is some tips to optimize your PHP code.

Set the max value for your for-loops before and not in the loop.

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

Error messages are expensive . Error suppressing is slow

Pre increment is faster than post increment.

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

$row[’id’] is 7 times faster than $row[id]
Use foreach in case of iterating array in the loop.

Use single quotes instead of double quotes.

Incrementing a global variable is 2 times slow than a local var. Incrementing an object property (eg. $this->prop++) is 3 times slower

Don't go on creating class,object,methods randomly.often it is too much overhead, each method and object call consumes a lot of memory

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

Try to use cache for your application.

Try comparing constant on the left side of the operand.eg. if(5==$five).will handle logical error

use isset for checking length of string which is faster than strlen() as it's language construct.
 eg. if (!isset($foo{5})) { echo "Foo is too short"; }
Avoid using regular expression.
eg.
preg_match("![0-9]+!", $foo);
vs
ctype_digit($foo);
ctype_digit is faster.

There are lot more to add will be followed in the next release.


Responses

  1. [...] – bookmarked by 3 members originally found by ci7626 on 2008-08-22 PHP Optimization tips. http://uttamkumar.wordpress.com/2008/07/09/php-optimization-tips/ – bookmarked by 3 members [...]


Leave a response

Your response:

Categories