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.

#Worst than foreach and while loop
for($i =0; $i < count($array);$i++){
echo 'This is bad, my friend';
}

#Better than foreach and while loop
$total = (int)count($array);
for($i =0; $i < $total;$i++){
echo 'This is great, my friend';
}

The above shows two different ways of writing a for loop. The first way includes the operation count into the loop while the second one pre-calculate the total number of loop outside it. The difference between these two is that the second doesn’t run count operation n times while the first one did. You can find this VERY interesting benchmarking on loops on  PHP.

Single Vs Double Quotes

Since i mentioned that benchmarking page on loops, it also includes the benchmark for single(‘) and double(“) quotes. Now, between these two what is the best one to use? It really doesn’t makes much differences. But i preferred to use  single(‘) quote because i don’t have to press shift? Just kidding (not). That’s one of the reason why i use a single quote over the double one. But the other reason is that PHP will scan through double quote strings for any PHP variables (additional operation) and usually i don’t mix my variables and strings into one. I usually use single quote instead. However, you might also have aware that if an empty string is declared using a single quote, it seems like there is a performance pitfall. You or I might want to take note of that. Basically, there is a dollar($) symbols in your string, try to avoid double quote unless its variable?

Pre increment vs Post increment

Well, increment a certain value also have a few ways to improve. We all know that there are many ways to increment integer values such as

$i++;
$++i
$i+=1;
$i = $i + 1;

Out of all these what way is the most efficient? In PHP, it seems like pre increment is better than the other ways of performing an increment. Its around 10% better than post increment? The reason? Some said that post increment made certain copy unlike pre increment. There isn’t any benchmark done for PHP but i found one on C++ which should be quite the same. Well, without a proper benchmark on this, i can’t really confirm this. Furthermore, it really doesn’t makes a big differences towards normal programmers but may affect those who are working towards micro optimization.  Nonetheless, many people do suggest pre over post increment in term of optimization.

Absolute Path VS Relative Path

Absolute path which is also known as full path compare to a relative path which will be better for PHP? Surprisingly, it seems that absolute path is better. Compare to relative path which might just help to screw up your include and require operation in PHP, absolute path doesn’t. Well, that’s the reason why i use absolute path. But the real reason is that using absolute path eliminate the need for the server to resolve the path for you. Simply to say, do you know where the file is located when you just look at a relative path or is it faster if i just throw you the full path?

Echo Vs Print

Yes! I know, echo is better. But how much better? Interested to know? I am interested. So i went to dig a bit on the internet and found some useful information for benchmarking between these two! Its around 12%-20% faster using echo compare to print when there is no $ symbol in the printing string. And around 40-80% faster if there is an $ symbol used in a printing string! This really demonstrate the differences between the keyword $ symbol used in PHP.

Dot Vs Commas Concatenation

Between dot and commas which way do you use to concatenate between two strings/variables? I personally used dot to concatenate my stuff. Such as the one shown below

$a = '10 PHP programming ';
$b = 'Improvement Tips';
#10 PHP Programming Improvement Tips
echo $a.$b;

I usually do the above. Instead of this,

$a = '10 PHP programming ';
$b = 'Improvement Tips';
#10 PHP Programming Improvement Tips
echo $a,$b;

Well, between these two which is more efficient? If you did visit the link for benchmarking between echo and print, you might have aware on the exact same test, they also have performed test case for dot and commas. The result shows that dot is more preferable if there are no variables or $ symbol involved which is around 200% faster. On the other hand, commas will help to increase around 20%-35% efficiency when dealing with $ symbols.

str_replace vs preg_replace vs ereg_replace

Ok! We have 3 string search function in PHP. Out of these three functions, which do you think will run the fastest? Some of you might have know, str_replace will run faster. Reason? str_replace doesn’t run any complex expression unlike preg_replace and ereg_replace. Well, maybe many of you might know that but it is not necessary always str_replace that runs fastest. If you have to call str_replace 5 times compare to preg_replace, which will run faster? (str_replace, of course) Wrong! preg_replace runs 86.99% faster than 5 str_replace function call! Basically, i also have such doubt and search for such benchmark. The benchmark really explains some doubts we have in these functions.

Find Timestamp

When you want to find out the time when your script starts running in order to get that timestamp to store it into your database. The first thing you do is to fire up your Google and search for some PHP function. Well, after PHP5 you do not have to do that. After PHP 5 you can easily retrieve the execution timestamp of your script by using

$_SERVER['REQUEST_TIME']

This could really save some time digging for something that already exist within your reach.

explode Vs preg_split

Well, when you want to split a string what do you use in PHP? I usually used explode because it support even PHP4.0 and that’s also what i was taught by my ex-colleagues. The answer in term of efficiency is explode. Split supports regular express and this makes it quite the same comparison between str_replace and preg_replace, anything that have regular expression support will usually be a bit more slower than those that doesn’t support it. It took around 20.563% faster using explode in PHP.

Other Benchmarks

I believe this list can go on forever with such great benchmarking site i found. It basically shows you most of the benchmarking between PHP functions or those articles that claim whatever stuff is better than the other in PHP but doesn’t provide you with any real evidence on their article. In this article, hopefully i have provided you with the necessary information for you to perform some micro optimization and also other more of such optimization through the benchmarking site.

Summary

I believe many of you have see all these information floating around the internet. But the only differences i see is that they don’t really provides you with the real interesting part of this article, that is the benchmark of each test. This article really help me a lot with all the figures and testing given by all these great benchmarking site. Hopefully it also gives you the same result.

P.S: Most of these benchmark sites are run on real-time.

 

Like this post? Share it!

digg 48 10 PHP Micro Optimization Tips reddit 48 10 PHP Micro Optimization Tips stumbleupon 48 10 PHP Micro Optimization Tips delicious 48 10 PHP Micro Optimization Tips furl 48 10 PHP Micro Optimization Tips technorati 48 10 PHP Micro Optimization Tips google 48 10 PHP Micro Optimization Tips myspace 48 10 PHP Micro Optimization Tips facebook 48 10 PHP Micro Optimization Tips twitter 48 10 PHP Micro Optimization Tips
share save 171 16 10 PHP Micro Optimization Tips

About Clay

I am Clay who is the main writer for this website. I own a small web hosting company in Malaysia and i'm available to be hired as individual contractor on elance or odesk. You can find me on twitter.
This entry was posted in Developer, Informative, Techniques, Tips And Tricks, Web Development and tagged . Bookmark the permalink.

23 Responses to 10 PHP Micro Optimization Tips

  1. Bruno Cassol says:

    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. Chris says:

    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. Clay says:

    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. SeanJA says:

    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. Clay says:

    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. Pingback: SEO For Beginners A Guide :

  7. Aaron McGowan says:

    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

  8. Aaron McGowan says:

    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.

  9. Clay says:

    Hey Aaron, Thanks for sharing! Very informative :)

  10. Aaron McGowan says:

    @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 :)

  11. chris says:

    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/

  12. Aaron McGowan says:

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

  13. Clay says:

    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.

  14. unreal4u says:

    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 :)

  15. Clay says:

    hey unreal4u, thanks for sharing the result of your testing :D

  16. Pingback: Brandon Savage’s Blog: Micro Optimizations That Don’t Matter | Webs Developer

  17. Les says:

    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.

  18. Aaron McGowan says:

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

  19. Clay says:

    @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?)

  20. Aaron McGowan says:

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

  21. Clay says:

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

  22. Just want to say – interesting article – but more than that – i love the design of your site. Very snazzy.

  23. Clay says:

    Thanks ! I REALLY APPRECIATE IT :D