Home > PHP > Optimize your PHP Code – Tips, Tricks and Techniques

Optimize your PHP Code – Tips, Tricks and Techniques

October 24th, 2008

  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.
    		switch( $name )
    		{
    			case 'saiful':
    			// do something
    			break;
    
    			case 'ekram':
    			// do something
    			break;
    
    			case 'arif':
    			// do something
    			break;
    
    			default:
    			// do something
    			break;
    		}
    
    		// is better than
    
    		if( $name == 'saiful' )
    		{
    			// do something
    		}
    		else if( $name == 'ekram' )
    		{
    			// do something
    		}
    		else if( $name == 'arif' )
    		{
    			// do something
    		}
    		else
    		{
    			// do something
    		}
    		
  15. Error suppression with @ is very slow.
    		$name = isset( $id ) : 'saiful' : NULL;
    		//is better than
    		$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.
  21. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
  22. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
  23. Just declaring a global variable without using it in a function also slows things down(by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
  24. Methods in derived classes run faster than ones defined in the base class.
  25. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.
  26. 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.
  27. 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. OP code caches are useful so that your script does not have to be compiled on every request
  28. 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( $name ) < 5 )
    		{
    			echo "Name is too short";
    		}
    
    		// is better than
    
    		if( !isset( $name{5} ) )
    		{
    			echo "Name is too short";
    		}
    		
  29. 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.
  30. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
  31. Do not implement every data structure as a class, arrays are useful, too
  32. Don’t split methods too much, think, which code you will really re-use
  33. Make use of the countless predefined functions
  34. If you have very time consuming functions in your code, consider writing them as C extensions
  35. Profile your code. A profiler shows you, which parts of your code consumes how many time.
  36. 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%
  37. Use ; tags when declaring PHP as all other styles are depreciated, including short tags.
  38. Never trust variables coming from users (such as from $_POST) use mysql_real_escape_string when using MySQL, and htmlspecialchars when outputting as HTML
    		//a safe query
    		$_user 		= mysql_real_escape_string( $user );
    		$_password 	= mysql_real_escape_string( md5( $password ) );
    
    		$query 		= sprintf( "SELECT * FROM user_info WHERE user='%s' AND password='%s'", $_user, $_password ); //safe output echo htmlspecialchars( "<a href='test'>Test</a>", ENT_QUOTES );
    
    		//output: <a href='test'>Test</a>
    		
  39. Avoid using plain text when storing and evaluating passwords. Instead use a hash, such as an md5 hash.
    		$user_input = 'myPassword';
    		if( md5( $user_input ) == $md5_password_from_database )
    		{
    			//login here...
    		}
    		
  40. Avoid the PHP mail() function header injection issue.
  41. Unset your database variables (the password at a minimum), you shouldn’t need it after you make the database connection.
  42. Use sprintf instead of variables contained in double quotes, it’s about 10x faster.

Helpful Resources & References:

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • BlogMemes
  • email
  • LinkedIn
  • Live
  • Print
  • Taggly
  • TwitThis
  • Yahoo! Buzz

$@!ful PHP , , , , , , , ,

  1. Anees
    October 25th, 2008 at 09:46 | #1

    Good Work Saif…

  2. Adil Farid
    October 25th, 2008 at 11:55 | #2

    Great Article Saif. It really inspired me…… INSHALLAH it will help me alot in improving my code.
    Thanks

    Adil Farid
    Junior PHP Programmer
    Dynamism IT Solutions
    Peshawar
    Pakistan

  3. October 25th, 2008 at 12:26 | #3

    Nice work Saiful. Keep on

  4. October 25th, 2008 at 14:23 | #4

    Nice compilation.
    But it seems you have misplaced the comment at:
    3. Use echo’s multiple parameters instead of string concatenation
    Which means, using the ‘,’ one is better.

    Hope that helps Everyone, So please change the comment to the bottom one.

    Good luck All …
    -HumaN

    PS: pls delete the previous comments I made, there was some problem while i was posting… Thank you.

  5. October 25th, 2008 at 14:30 | #5

    Thanks Mr. HumaN.

    Actually I wrote the article in Notepad++ using HTML and just paste it WordPress’s editor.
    The WordPress’s editor made the change.

    Thanks again for your suggestion.

  6. December 12th, 2008 at 14:27 | #6

    The links to http://www.go4expert.com does not work in Helpful Resources & References and the reason is you have an error in the file name

    You are linking to

    http://www.go4expert.com/forums/showthread.PHP?t=13769

    but it should be

    http://www.go4expert.com/forums/showthread.php?t=13769

    it should be php and not PHP in filename

  7. December 15th, 2008 at 10:52 | #7

    Thanks Shabbir for your correction. It was an unexpected mistake and I am sorry for that. Now it is in correct form.

  8. March 6th, 2009 at 03:52 | #8

    Great article, just couldn’t resist to blog about it, since it describes thinks I’ve been preaching for years.

    http://originalcopy-on.blogspot.com/2009/03/small-php-optimizations-anyone-can-and.html

  9. March 31st, 2009 at 20:59 | #9

    I wasnt aware of all of this, thank you.

  10. snoutz
    May 12th, 2009 at 11:42 | #10

    great article from expert..keep going..:)

Comment pages
  1. No trackbacks yet.