PHP Optimization – Good Coding Practice

I have been into PHP for a while, and I often wonder if my programming style slows down PHP. Regardless of which programming/script language used, there are always coding practices which you can adhere to that would improve and optimize the performance of the program/website.

I have compiled a list specific to PHP, feel free to comment and let me know if any of these are in any way incorrect or if I have missed out some important details!

The benchmarks are (unless otherwise stated) 100,000 repetitions, and the execution time monitored, then repeat this procedure further 100 times to get a mean (average) result. Results are in seconds.

I realise that this is not the best way to benchmark some of these things, however the information provided is only as reference and useful information, much of coding decisions depend on specific development situations. Benchmarks area always not 100% accurate, but these should give you some ideas.

  • echo v.s. print: echo is faster!
    Benchmark result: calling echo and print each 100,000 times, then record down and repeat 100 times to get the mean of the execution time.
    echo: 0.0103772668
    print: 0.0131989881.
    In this case echo is 21.4% faster than print.

  • is_numeric v.s. ctype_digit: is_numeric is faster!
    Benchmark (same amount of calls as above) results:
    is_numeric: 0.0343670035
    ctype_digit: 0.039338827
    In this case is_numeric is 12.6% faster than ctype_digit.

  • echo with arguments v.s. echo with string concatenation: echo with arguments is faster!
    Same benchmark as above, results:
    Using arguments: 0.0158054996
    Using string concatenation: 0.0196612982
    In this case echo with arguments is
    19.6% faster.

  • date(‘U’) v.s. time(): time() is A LOT faster!
    Same benchmark as above, but only 1000 x 100 otherwise execution time will exceed 120 seconds:
    date(‘U): 0.1652520891
    time(): 0.0005419447
    In this case time() is many times faster than date(‘U).

  • Double quote " v.s. single quote ‘ (for strings): single quote is faster!
    Same benchmark as above, results:
    Double quote: 0.0430300813
    Single quote: 0.0401632808
    In this case single quote is 6.7% faster.

  • If statement, the more likely false condition written first: faster than if condition is written latter!
    Eg: writing if(false && true) as oppose to if(true && false).
    Same benchmark as above, results:
    False written first: 0.0116060285
    False written second: 0.0125979803
    In this case it is good practice to write the more likely false condition first, as PHP won’t have to check for the second condition if the first is false. False written first is 7.2% faster.

  • Pre-increment v.s. post-increment: pre-increment is faster!
    Same benchmark as above, results:
    Pre-increment: 0.0108520968
    Post-increment: 0.0133335854
    In this case pre-increment is 19% faster.

  • == v.s. ===: === is faster!
    Same benchmark as above, results:
    ==: 0.0137838533
    ===: 0.011689375
    In this case === is 15.2% faster.

  • casting v.s. intval(): casting is faster!
    Same benchmark as above, results:
    casting: 0.0665502957
    intval(): 0.011689375
    In this case casting is 82.4% faster.

  • Uppercase boolean v.s. lowercase boolean: equally fast!
    Same benchmark as above, but 20000 x 100. Results:
    Uppercase: 0.0260072494
    Lowercase: 0.0260037331
    In this case neither stood out in terms of performance. Many people have said that lowercase is much faster, however the results above are exactly the same, considering the variance of the results.

  • Uppercase nullv.s. lowercase null: equally fast!
    Same benchmark as above, but 20000 x 100. Results:
    Uppercase: 0.0252593086
    Lowercase: 0.0257853128
    Again, due to variance we cannot really say for sure that one is faster than the other. My general impression though running the test a few times for each of them, uppercase null seems to be slightly faster than lowercase. This is only my feeling and I would say the difference is not significant enough to pick out a clear winner.

  • For Loop v.s. While loop v.s. Do-While loop: While loop is the fastest!
    Same benchmark as above, results:
    For Loop: 0.0088448026
    While Loop: 0.0001337801
    Do-While Loop: 0.0070282102
    According to the results, while loop seems to be the fastest, and do-while has around the same performance as the for loop.

  • ereg_replace() v.s. preg_replace(): Depends on the regular expression, but str_replace() is faster than both.
    Same benchmark as above, results:
    ereg_replace(): 0.2183233668
    preg_replace(): 0.2578533819
    In the test, I used a moderate regular expression which would try to match and see if the email address is valid. preg_replace has been known to be more efficient, but in this case ereg_replace seems to be faster. It really depends on how complex the regular expression is and what you are trying to match. The fastest way is to not use regular expression at all, and utilize the str_replace() function in PHP.

  • Different ways of writing for-loops.
    Same benchmark as above, results:
    for($i=0;$i<100000;$i++): 0.0086089157
    for(;++$i<100000;): 0.0079079485
    The second way of writing for-loop seems to be slightly faster (by 8.1%).

  • split() v.s. explode(): explode() is faster!
    Same benchmark as above, results:
    split(): 1.052375164
    explode(): 0.2835274458
    Although explode a lot faster , remember that sometimes split() is needed and more useful as it is possible to take regular expressions, thus the trade-off for speed. The bottom line is if you do not need the regular expression support, then definitely go with explode().

  • strlen() v.s. isset(): isset() is faster!
    Same benchmark as above, results:
    strlen(): 0.03381763
    isset(): 0.01284088
    Using isset is much faster to determine the string length. The syntax for this is:
    if(!isset($test{10}) echo ‘String is not 10 characters long.’;
    Using isset() is nearly 3 times faster than calling strlen().

  • str_replace() v.s. strtr():
    Same benchmark as above, results:
    str_replace(): 0.10412544
    strtr(): 0.09002823
    In the result above, strtr() is 13.5% faster. However, these 2 functions do differ slightly, strtr() being used more conveniently when we are wanting to replace multiple values in some string.

  • Error suppression (using @) v.s. no error suppression: No error suppression is much more efficient!
    Same benchmark as above, results:
    with @: 0.11822414
    without @: 0.02433966
    Not using @ (error suppression) is over 5 times faster than with error suppression. If error suppression is needed, error_reporting(0) or similar should be used to avoid the performance degradation.

 

Comments and suggestions are welcome, I will edit my post according to your suggestions!

Source where I got some of the comparison ideas from (I did the benchmarks myself):
http://bitfilm.net/2007/08/24/tips-for-faster-php-scripts/
http://bitfilm.net/2007/09/07/more-tips-for-faster-php-scripts/

4 Responses to “PHP Optimization – Good Coding Practice”

  1. james Says:

    Nice post you have here – I’ve been searching for a echo vs print but found alot more in here. Nice job you’ve done. Can I borrow this article from you with pingback of course?

  2. pucadinga Says:

    Off course, no problem! Glad you like it! :)

  3. Andres Says:

    There’s something wrong in this one:

    casting v.s. intval(): casting is faster!
    Same benchmark as above, results:
    casting: 0.0665502957
    intval(): 0.011689375

    If intval() is executed in less time, why do you say that casting is faster?

  4. Ries van Twisk Says:

    Althougbh it’s nice to know what functions are faster then other similar functions.
    I am a strong believer that people shouldn’t do this micro optimalisations (unless you really really really have to).

    Micro optimalisations are best handled and solved during compiling and interpreting of code, and not by humans.
    As you can clearly see of some example (not all) they make code pretty much unreadable.

    I find that the following arguments mentioned above are bogus event:
    - date(ā€˜U’) v.s. time() : Both functions do something different
    - if(false && true) as oppose to if(true && false) : This is obvious because when the code sees fails he will not do any more if evaluations. It’s like saying that two time print is slower then one times print …;
    - Error suppression (using @) v.s. no error suppression : Under some situations you have to do that, unless you want to use a fancy try/catch or if/then the solve it… which make the version without @ slower anyways and the slowness comes really from the reporting itself then the @. In production you would set error_reporting(0) anwyays
    - The example given in strlen() v.s. isset(): isset() is faster! is weird, it makes code unreadable, interesting code though… but unreadable.
    - Pre-increment v.s. post-increment: pre-increment is faster! They do different things and sometimes you need one or the other, unless you are simply looping.

    anyways…. zend should fix the compiler for some of the mentioned items :)


Leave a Reply