Optimize PHP Code

by Dinesh 2012-05-31 17:18:02

1. If a method can be static, declare it static. Speed improvement is by a factor of 4

2. echo is better than print
echo( 'CHECKMATE: PLAY with PROBLEMS' );
// is better than
print( 'CHECKMATE: PLAY with PROBLEMS' );


3. Use echo’s multiple parameters instead of string concatenation
echo 'PLAY', 'WITH', 'PROBLEMS';
// is better than
echo 'PLAY' . 'WITH' . 'PROBLEMS';


4. 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.
echo 'a string ' . $name;
// is better than
echo "a string $name";


5. Use functions outside of loop. Otherwise function gets called each time.
$max = count( $array );
for( $i = 0; $i < $max; $i++ )
{
// do something
}
// is better than
for( $i = 0; $i < count( $array ); $i++ )
{
// do something
}


6. Unset your variables to free memory, especially large arrays.

7. Avoid magic functions like __get, __set, __autoload

8. require_once() is expensive

9. Use full paths in includes and requires, less time spent on resolving the OS paths.
include( '/var/www/html/your_app/test.php' );
//is better than
include( 'test.php' );


10. If you need to find out the time when the script started executing, $_SERVER['REQUEST_TIME'] is preferred to time()
11. See if you can use strncasecmp, strpbrk and stripos instead of regex

12. str_replace is better than preg_replace, but strtr is better than str_replace by a factor of 4

13. 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.

14. It’s better to use select statements than multi if, else if statements.
01 switch( $name )
02 {
03 case 'saiful':
04 // do something
05 break;
06
07 case 'ekram':
08 // do something
09 break;
10
11 case 'arif':
12 // do something
13 break;
14
15 default:
16 // do something
17 break;
18 }
19
20 // is better than
21
22 if( $name == 'saiful' )
23 {
24 // do something
25 }
26 else if( $name == 'ekram' )
27 {
28 // do something
29 }
30 else if( $name == 'arif' )
31 {
32 // do something
33 }
34 else
35 {
36 // do something
37 }


15. Error suppression with @ is very slow.
1 $name = isset( $id ) : 'saiful' : NULL;
2 //is better than
3 $name = @'saiful';


16. $row['id'] is 7 times faster than $row[id]

17. Error messages are expensive

18. Close your database connections when you’re done with them

19. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.

20. Incrementing a global variable is 2 times slower than a local variable.

Tagged in:

829
like
0
dislike
0
mail
flag

You must LOGIN to add comments