Web Design SEOHello Everyone,

As a Sr. Web Programmer here at Noam Design, I always look for ways to optimize the code I develop for efficiency. I primarily do back-end programming with PHP and MySQL. Today I am going to share with you some tips that I have personally encountered while programming with PHP. I hope these 15 tips will help you optimize your PHP code and get you into the habit of looking for alternative ways or patterns of writing robust code. Also don’t forget to document your code properly! Enjoy!

  1. echo is faster than print.
  2. 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.
  3. Use echo‘s multiple parameters (or stacked) instead of string concatenation.
  4. Use pre-calculations, set the maximum value for your for-loops before and not in the loop. ie: for ($x=0; $x < count($array); $x), this calls the count() function each time, use $max=count($array) instead before the for-loop starts.
  5. Unset or null your variables to free memory, especially large arrays.
  6. str_replace is faster than preg_replace, str_replace is best overall, however strtr is sometimes quicker with larger strings. Using array() inside str_replace is usually quicker than multiple str_replace.
  7. else if statements are faster than select statements aka case/switch.
  8. Close your database connections when you’re done with them.
  9. $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.
  10. Use <?php … ?> tags when declaring PHP as all other styles are depreciated, including short tags.
  11. Use strict code, avoid suppressing errors, notices and warnings thus resulting in cleaner code and less overheads. Consider having error_reporting(E_ALL) always on.
  12. When using header(‘Location: ‘.$url); remember to follow it with an exit; as the script continues to run even though the location has changed or avoid using it all together where possible.
  13. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
  14. Methods in derived classes run faster than ones defined in the base class.
  15. Error suppression with @ is very slow.

More to come!

ABOUT THE AUTHOR

Next generation websites that work on all devices, feature award winning web design, state-of-the-art web technologies, and powerful administration tools to edit and manage your site anytime, anywhere! Follow us on Twitter and subscribe to the feed to stay tuned.

24 Comments

  1. Raymond
    December 13, 2008 at 12:29 pm

    this was really helpful. I’m gonna start converting my code now.

    Reply
  2. EllisGL
    December 16, 2008 at 8:46 am

    #8 really should be “free your results with mysql_free_result” then should make #9 this..

    #11 and #15 are talking about the same thing..

    #12 if you don’t use a die() / exit() after the header, security issues can arise


    #16 Use ++$i instead of $i++ (Only certain times do you need to $i++).

    #17. Don’t use concatenation when echoing out stuff, use arguements (comma separated). IE: echo ‘My name is’,$name,’.';

    #18. Use Do/While loops where possible. IE:
    $sql = ‘SELECT * FROM `cache_menu`';
    $qry = mysql_query($sql) or die($sql.’ ::: ‘.mysql_error());
    $x = mysql_num_rows($qry);

    if($x > 1)
    {
    do
    {
    $row = mysql_fetch_assoc($qry);
    }while(++$b<$x);
    }

    I have found this to be over 10% faster.

    Reply
  3. EllisGL
    December 16, 2008 at 8:47 am

    my #18 – the if statement should be $x > 0

    Reply
  4. Loïc Hoguin
    December 16, 2008 at 4:41 pm

    I agree with #4 (although it’s being fixed IIRC, so will be soon irrelevant), #8, #10, #11 and #12. #11 using E_ALL|E_STRICT however. Of course writing strict PHP code makes me kinda agree with some other points but not because of “optimization” reasons.

    The other points (#1, #2, #3, etc.) are stupid. You’re doing what is called micro-optimization. You basically make your script go a few nanoseconds faster than before by following these tips. It’s not worth it. When optimizing the first thing you should do is find *where* you should optimize (using xdebug+cachegrind for example). When you’ve found what takes time you try to understand why and fix it. Fixes rarely involve micro-optimization. Making your script load one less file is going to be much more efficient than any kind of micro-optimization you can do, for example.

    #5 is potentially misleading. I’d like to have some proof that the memory is actually freed. I don’t know the specifics for PHP, but when a process frees memory on Linux (for example), the new free memory cannot be used by another process. My guess would be that if you don’t use modphp to run your PHP script, then this tip doesn’t work because when using CGI each instance would have its own process.

    #15 is misleading too, it’s not the @ operator that is slow. It’s the error or warning. It’s going to be slow whether you silence it or not. See http://vega.rd.no/article/php-performance-error-suppression for more details.

    Reply
  5. Michał Bachowski
    December 17, 2008 at 8:47 am

    I beg you – stop repeating #1, #2, #4, #7, #16 and #18. You`re right – this approach is faster. However the difference is negligible! Check it out: http://www.phpbench.com . Difference 10µs, 50µs or 100µs for 1000 calls? Come one…

    #9 and #10 PHP shouldn`t allow at all.

    #11 ok, error_reporting( E_ALL | E_STRICT ), but I hope that display_errors is set to 0 on production server…

    #12 is not optimizing but good practice.

    #15 @ is indeed slow – even if error does not occur – 2 additional actions are taken ( “error_reporting( 0 )” before and resetting error reporting to previous state after calling statement that is “silenced”). So – @ is slow.

    The real optimization is when you use kind of caching system, refactoring your DB scheme or SQL queries to run your app faster.

    Regards

    Reply
  6. Richard Castera
    December 17, 2008 at 8:12 pm

    Hello EllisGL,

    I would like to thank you for taking the time to read my article and for your comment! I have written some responses to some of your comments below:

    #8 really should be “free your results with mysql_free_result” then should make #9 this..
    In the PHP Documentation, mysql_free_result() only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script’s execution.
    #11 and #15 are talking about the same thing..
    Well in essence they are about the same topic (avoid suppressing errors) but #11 outlines the technique of using error_reporting(E_ALL) to aid you in writing cleaner code while #15 mentions that the error suppression symbol “@” runs slow.
    #16 Use ++$i instead of $i++ (Only certain times do you need to $i++).
    This you are indeed correct about. This is more efficient. Although I did not mention the efficiency of both methods in the post, your addition is very much appreciated.
    #18. Use Do/While loops where possible.
    Again, you are correct about this. It is indeed 10% faster in my tests as well. Thanks again for the addition!

    Reply
  7. Richard Castera
    December 17, 2008 at 8:17 pm

    Hello Loïc Hoguin,

    Thank you very much for your input and for posting a comment! In response to your comments,

    (#1, #2, #3, etc.)
    While I agree with you. If you think it terms of large scale applications changing several lines of code with theses tips could add up to some considerable load speed.

    (#5)
    I’m not totally sure on this one but the point is not only writing code more efficiently but it’s good programming practice to destroy your variables and let other users who could potentially have to look or re-factor your code a clear indication of what you were trying to accomplish not evreyone thinks or codes the same way.

    (#15)
    Upon reading the article in your link, if your read it carefully, it states that it is indeed a little slower:
    “The graph clearly shows that @-suppression is a little bit slower than not using @-suppression when no error is triggered. However, when triggering a warning, even though it is stopped by error_reporting() settings, takes a lot of time. The @-suppression only adds a tiny amount of overhead to that value.”

    Most importantly the paragraph below states:
    However, using @-suppression can be dangerous. If you suppress a fatal error, the script will terminate with no indication as to why it terminated. The fact that there is some speed penalty also means that you should try to avoid it in tight loops.

    Reply
  8. Richard Castera
    December 17, 2008 at 8:25 pm

    Hello Michał Bachowski,

    Thanks so much for your comment! You are correct about the real optimization being in caching systems, refactoring, etc. Thanks!

    Reply
  9. hasin hayder
    December 18, 2008 at 2:46 pm

    mmm, i appreciate your article but to be honest, you need not to care about the microseconds you gains by using echo over print, single quotes over double quotes and so on. current hardware are so fast that it merely does matter changing your code to these substitutes.

    rather, i would suggest you to focus on scalability, improvement of algorithm, caching and using cutting edge scaling techniques which is really helpful for writing you next working app.

    good luck.

    Reply
  10. Deepak
    December 20, 2008 at 7:05 am

    thx u so much for this blog..and reply

    Reply
  11. Azeem Michael
    December 20, 2008 at 12:42 pm

    ++$i or $i++ makes no difference in optimization. Only effect it has is in program logic. For e.g., using $i++ tells the parser to use variable $i first then add 1. ++$i adds 1 before using $i. Time “T” needed to iterate through “n” elements is T(n) for both.

    Reply
  12. Girish
    December 25, 2008 at 5:04 am

    Since last few months I am doing a course in web designing. So, I find your post to be a very useful one. You will be glad to know that I have included your post in my bookmarked items.

    Reply
  13. Azeem Michael
    December 26, 2008 at 11:31 pm

    Has anyone ever realize how when we write functions that return value in if/else condition we check for else condition even though we don’t really need to. For e.g. consider following:

    function doSomething(){

    if(condition)
    return true;
    else
    return false;
    }

    I don’t believe one needs to check for an else, because, if our condition is meet then php is going to grab the true value and leave the function anyway — the else condition would never be checked. However, if our condition fails, then the parser would drop out of the condition and it would run the rest of the code. I believe the proper way of writing above code is as follows:

    function doSomething(){

    if(condition)
    return true; //also, we don’t need “{}” brackets if our if statement has only one line.

    return false;
    }

    Reply
  14. mario
    January 4, 2009 at 12:05 pm

    Those recommendations are all nuts. Single and double quotes for strings make a neglectable difference. It’s the tokenizer who parses your PHP code The parser or PHP core doesn’t ever see this optimization.

    Likewise unset() doesn’t actually free any memory. Only the garbage collector does. It looks for variables marked as unser. But that’s about it.

    If you wanted a serious speed optimizations, go look for “Parameterized SQL” and bind statements. Optimize your queries. Get rid of configuration data in SQL (use plain PHP constants / variables instead). Unfold loops into recursive code / vice versa, depending on what happens. And: sometimes it is faster to execute an external application system(“mogrify ..”) that is optimized for special purposes, than to do it in PHP by hand.

    Reply
  15. Vincent
    January 17, 2009 at 4:23 am

    What a nice post.I like it.
    Thanks.

    Reply
  16. Hugo
    February 11, 2009 at 2:29 pm

    Nice post. Most blogs or not very informative. At least I learnt something with yours.

    Reply
  17. Victor
    May 25, 2009 at 11:51 pm

    Amazing post. Thanks for sharing.

    Reply
  18. Web Site Developers New York
    August 13, 2009 at 8:26 am

    Good informative post. Thanks for sharing with us.

    Reply
  19. Alex
    August 31, 2009 at 1:19 am

    So one quick question. Does PHP work better all spaced out or better smashed together. What I mean by this is would it be better to use:

    if ( $var1 == $var2 )
    {
    echo “Hi!”;
    }

    or would it be better to use it like this:

    if($var1==$var2){echo “Hi!”;}

    I know you could do the second one above another way but I’ve made it like that for explanation’s sake.

    Reply
  20. Gerard
    September 1, 2009 at 12:31 pm

    Hi Alex – either way is fine. If you have thousands of lines of code, the first way will be more manageable and easier to work with.

    Reply
  21. Alex
    September 2, 2009 at 3:57 pm

    Ok, thank you very much for your prompt response and your help!

    Reply
  22. Webplore
    October 29, 2009 at 12:07 am

    Just came across your blog but got some useful information, keep posting.

    Reply
  23. Web Development
    May 1, 2010 at 1:31 am

    Great Tips. keep up the good work

    Reply
  24. Techie Talks
    February 22, 2013 at 2:01 am

    Isn’t it php is smart enough that it automatically unsets a variable after running an instance?

    Reply

Leave a Reply

Web Analytics