10 PHP Micro Optimization Tips

There are many ways to improve the way you write your PHP code. And we can easily increase the efficiency of our code just by putting in some effort during development. However, there might be some unknown information that you might not aware in PHP that can help improve your code. In this article, i will try to provide you with some tips that can serve as micro optimization for your code and could also add on to the list of knowledge that you have in PHP. We will also look at many benchmarking of these tips where possible!

Loop

Every program will required certain amount of loop. And loop is considered as efficiency killer if you have many nested loop (means loop in a loop) as one loop will required to run 'n' times and if you have 1 nested loop, this means your program will have to run n2 times. Well, i think you can do the math. But we are not talking about this. There is something more interesting about loop in PHP. There are many ways we can define a loop in PHP. But how do you know which one is the best way to loop your data? Apparently, using a for loop is better than foreach and while loop if the maximum loop is pre-calculated outside the for loop! What do i mean? Basically is this.

23 thoughts on “10 PHP Micro Optimization Tips

  1. Good tips.

    Just remember: optimization should only be used when really necessary as it frequently degrades code quality. It is important to identify the bottlenecks and start optimizing by them.

    Keep writing!

  2. Not to be super critical, but there is only one Concatenation character in PHP, which is the dot "." ... the comma is used in echo statements as argument separators, just as you would use them in function calls [like doSomething(123,"yeah",true);].

    If you were to take the commas out of the context of the echo statement, you will get a Parse Error 🙂

  3. Oh..really...? HeHeHe.. (Evil laugh)

    P.S: its true for print not echo, i like your dp Chris 🙂

    Bruno: Correcto!

    Just to add this up, micro optimization benefit is really small and sometimes it will be better to write code in term of maintainability rather than mess it up just for this little optimization. But its rather interesting how these benchmarking is being done to gain extra knowledge in PHP (for some who will ask which function is faster or better? I guess you will be able to answer rather than 'they are the same')

  4. The commas also work in var_dump the same way that they work with echo.

    However, like I said on dzone: [The benchmarks] will be wrong tomorrow as they keep improving the language.

  5. I agree with you Sean! But I just appreciate what these guys have done for us and most of the benchmarking sites are running on real time 🙂

  6. 1. The "Loop". Correct, calling count numerous times is a performance hit. However, you might also want to add the inline count/variable declaration. Something like this:
    for( $i = 0, $size = count($stack); $i < $size; ++$i ) { ...

    You might always want to add that using size instead of less then I have found be better in other languages such as C++, but I have personally never benchmarked this in PHP. You might want to try it and you may be surprised about the results.

    2. Something interesting I am not sure if you know about, but when using foreach loops ...
    foreach( $stack as $offset => $value ) {
    ...
    }

    Did you know that after the foreach loop has been completed, the variable $value now exists within the current scope? Well, you may want to add an unset($value). Also, I have found using the amperand operator for reference assignment also helps performance with PHP foreach:

    foreach( $Stack as $offset => &$value ) {
    ...
    }

    3. Pre/Post Increment
    As you state pre-increment is preferred for performance. This is true along with the fact that it is faster (sometimes). However, with the way technology is moving now a days - the pre-incrementer for compiled code such as C++, it honestly does not matter that much if you use pre or post incrementing. I still however prefer pre-incrementing.

    4. ereg_replace
    This function is depreciated as of PHP 5.3. Stop using it. 🙂

    Anyways, that's my rant! If you have any questions or concerns about my comments feel free to let me know 🙂

    Aaron McGowan

  7. Also, I would like to add that one of the reasons a foreach loop in PHP is slower then while or do-while or for loop is the fact that a foreach loop creates of copy of the values instead of directly accessing them like you would in a for loop.

  8. @Clay: Not a problem, any time! 🙂

    Also, I guess I should also add when using the following:

    foreach( $stack as $offset => &$value ) {

    The foreach loop does not perform a copy (or at least that I can tell from even digging down into the core PHP C code) and it simply just assigns by reference causing a much less performance hit 🙂

  9. Every time see one of the "optimization" articles, my hopes for PHP developers everywhere sinks a little. Giving tips like these that *might* shave milliseconds off your code isn't particularly useful. Why not give helpful hints on things that can really help code go faster like refactoring or caching?

    These micro-optimization tips give developers false hope that, by using them, they can make a difference in their applications. When in reality, they just don't make much of a difference at all.

    Want some better suggestions? Try this post instead: http://www.brandonsavage.net/micro-optimizations-that-matter/

  10. @Chris: I completely agree with you. I thought I would just make my comment about it thats about all. I truly do not refactor my code to confine with "optimization" techniques in the "micro" land. (examples like above). I simply just write them properly from the get go and refactor chunks of code.

  11. Chris, i believe because this is micro optimization instead of 'Micro' optimization? The article you suggested is mentioning about optimization in PHP with the 'micro' as highlighted but it is really just optimization instead of micro optimization. The tips here is to suggest you to gain some knowledge but it is not a must to apply micro optimization. In fact, i believe this is actually more useful than just pure optimization as the majority of people would have already known that caching or refactoring produces better performance. What everyone missed out might just be the detail of each function run in PHP. Without benchmarking would you ever know which function in PHP run faster? (Just by purely believing PHP team is the best, they will do the best they can, sounds like an idiot to me)

    Being a good programmer is not all about writing codes. This knowledge is necessary to proceed further in this field. In reality, people do ask questions like 'Why does PHP provide so many similar functions?! Which one runs faster? How fast?' You can't seriously think this isn't useful. Short-sightedness won't bring any programmer further in their career. However, for people who are seeking for optimization or better performance, Chris suggested article might just gives you some valuable assistance.

  12. Very nice and informative blog, just crossed with it today ... Congratulations to the admin and all cooperators.

    Just to add a benchmark, som time ago i tested if-elseif-else, switch and if - if-else.

    Results?
    switch is quicker when number of comparisons is over ~20000.
    if-elseif-else is quicker when number of comparisons is under ~500.
    if-if-else is quicker when number of comparisons is between ~500 - ~1000 and also when number of comparisons is under ~50.

    So, generally it would be better to use if- if-else because i don't see any reason to use over 1000 different cases in one page.

    50 comparisons:
    switch: no number found: 0.000021935 secs. Mem: 95kiB / 116kiB
    if-elseif-else: no number found: 0.000009060 secs. Mem: 96kiB / 116kiB
    if - if-else: no number found: 0.000007868 secs. Mem: 96kiB / 116kiB

    if you want to do some tests, send me a mail 😉

    Greetings 🙂

  13. Let me say this once more only...

    The difference between using ' and " is not here nor there in the grand scheme of things regarding performance.

    Nor does the difference between echo() and print() - absolutely no difference to your performance, so PLEASE, PLEASE stop making these comparisons.

    From the professionals point of view (myself included), it is only amateurs that blog about those comparisons - people who actually have little experience on real world application development who continue to bang the drum.

    Seriously people, there are a 100 other things you could optimise first that would make a difference rather than fart about with redundant issues such as these.

    I hope I've [finally] made myself clear as if I see another blog post about saving a few thousandth of a second by using echo() instead of print() et al I'll hit that -beep- blog relentlessly - and I will bring it down.

  14. @Les:

    As a professional - you should know that echo and print are not functions so you should not be identifying them as such. They are language constructs - meaning they are simply used as:

    echo 'Hello World';
    print 'Hello World';

    Also - I agree about these items not being a big deal when it comes to applications. HOWEVER, they should be a part of a your coding standards as some of the above are excellent coding standards. As a business owner of a software and web application company, I have strict policy when it comes to coding standards and some of the above items within the post are included within our coding standards documentation.

  15. @Les : Oh god, let me repeat this for the few million times. The information HERE is to gain additional knowledge, MICRO optimization doesn't gives you HUGE optimization and it really doesn't matter in REAL world application. Hence, this is useless for most of you. Nonetheless, the additional knowledge of knowing the differences between each functions that is truly interesting in this article. I have stated this numerous times and i still get comment such as this. People are doing benchmark for this and there are people who ARE interested with such result (well, not you). 'Professionals' please refer to the comments before making intelligent comment. Your co-operation is highly appreciated. ( i wonder what kind of professional will praise themselves as one uh, bad one?)

  16. @Clay: Thank you! However, the above items in your post DO matter in real world applications. There is a difference between a successful application or not and you have stated some of them within your post along with a few of my comments.

  17. @Aaron : Yes, it does. Although it is insignificant, but many insignificant micro optimization from the start to the end might just make a big differences comparing someone who doesn't apply at all. However, people who already established a system without such knowledge at first might not be advisable to change their code because of such micro optimization. The key is don’t optimize blindly, and consider the tradeoffs that are inherent.

    While this article does bring out a lot of comparison on different functions in PHP. It is vital to consider the use of function that does make a differences though its small. Without knowing these, programmers will just blindly use whatever available to them and worry about optimization later. That is when refactoring or caching come into play. Basically, it's all come down to discipline.

Comments are closed.