12

What are some of the most expensive operations in PHP? I know things like overusing the @ operator can be expensive. What else would you consider?

3
  • 5
    why are you trying to catch these tiny perfomance problems? if your program is slow, it's not because of @ Dec 24, 2009 at 19:26
  • 4
    The "paypal $10 to Paul Tomblin" one is pretty expensive. But totally worth it. Dec 24, 2009 at 19:39
  • @valya I'm trying to get a sense of the different things that should be avoided where performance is concerned. I only use the @ operator as an example. Dec 24, 2009 at 19:45

10 Answers 10

22
  • serialize() is slow, as is eval(), create_function(), and spawning additional processes via system() and related functions.
  • beware of anything APC can't cache -- conditional includes, eval()ed code, etc.
  • Opening database connections. Always cache your connections and re-use them.
  • Object cloning
  • Regular expressions. Always use the normal string operations over a regular expression operation if you don't need the functionality of a regexp, e.g. use str_replace() over preg_replace() where possible.
  • Logging and disk writes can be slow - eliminate unnecessary logging and file operations

Some micro-optimizations that are good practice, but won't make much difference to your bottom line performance:

  • Using echo is faster than print
  • Concatenating variables is faster than using them inline in a double-quoted string.
  • Using echo with a list of arguments is faster than concatenating the arguments. Example: echo 'How are you ',$name,' I am fine ',$var1 is faster than echo 'How are you '.$name.' I am fine '.$var1
  • Develop with Notices and Warnings turned on. Making sure they don't get triggered saves PHP from having to run error control on them.
2
  • 2
    Exactly the kind of answer I'm looking for. Thanks @zombat!! Dec 24, 2009 at 20:05
  • In my experience, cloning an object is cheaper than instantiating a new one.
    – Josh Davis
    Dec 24, 2009 at 21:01
5

Rather than trying to figure out potential areas that are slow, use a profiling tool. Installing xDebug was probably one of the easiest and best things I've done to improve the code I write. Install with WinCacheGrind (or the correct version for your OS) for best results.

2
  • Agreed. I'm just thinking of things that one might want to commit to muscle-memory in order to automatically avoid. To my mind, profiling is best at showing you bottlenecks that you weren't otherwise aware of. Dec 24, 2009 at 19:38
  • Yes - great point. If your using a framework, you'll tend to find that most of the time is spent in that framework - and often - not a place you'll really be able to optimize. Something like APC can work wonders (or any opcode cache for that matter). Also, WinCacheGrind is pretty old, checkout kCacheGrind for Ubuntu (I ran a VM for just this one tool).
    – mr-sk
    Dec 24, 2009 at 20:25
4
 "Hello $name"

syntax is slower than

'Hello ' . $name

also __get() __set() __call(), etc are slow

and, if you care so much, you can use optimized structures from SPL

5
  • 1
    +1, I never knew that "Hello $name" was slower than "Hello " . $name =) Dec 24, 2009 at 19:30
  • PHP string interpolation is not what I would call "one of the most expensive operations in PHP". It's very fast. Yes, you're right: the interpolation example above is 20% or 25% slower relative to the concatenation example but that does not imply that interpolation is a major drag.
    – user213154
    Dec 24, 2009 at 19:41
  • neither do "@" or anything else. stop fearing features, fear your bad code Dec 24, 2009 at 19:42
  • 1
    @valya I appreciate where you're coming from but thats not a helpful comment. I happen to agree with you but at the same time I'm trying to get a list of gotchas that people should look out for when writing PHP. Let's face it, PHP is great but will not only let you hang yourself but will actively encourage it sometimes. Dec 24, 2009 at 20:04
  • and, if you care so much, you can use optimized structures from SPL - great point!
    – mr-sk
    Dec 24, 2009 at 20:28
2

Anything that's going though a network connection -- like calling a webservice, for instance : it'll generally take more time than doing an operation locally.

(Even if it doesn't cost much CPU, it'll cost time)

1
  • if this is not obvious for everybody than I dont know what is
    – Tonoslav
    Sep 10, 2020 at 8:45
1

I'd say SQL queries inside loops. Such as this:

foreach ($db->query('SELECT * FROM categories') as $cat)
{
    foreach ($db->query('SELECT * FROM items WHERE cat_id = ' . $cat['cat_id']) as $item)
    {
    }
}

Which, for the record, could be shortened into something like this:

$sql = 'SELECT c.*, i.*
          FROM categoriess c
     LEFT JOIN items i USING (cat_id)
      ORDER BY c.cat_order';

foreach ($db->query($sql) as $row)
{
}
4
  • I would think the second example would be slightly /more/ expensive since there is an assignment instruction. Dec 24, 2009 at 19:39
  • 1
    Oh yeah? So what is it? The question is "what is the most expensive stuff in PHP" and the answer is "anything that you put inside a loop that doesn't belong there." But you're right, it's so much more important to take care of those pesky single-quotes!
    – Josh Davis
    Dec 24, 2009 at 19:40
  • @Josh I think with your example, the better solution would be to move the $db->query() outside of the foreach evaluation. So do: $result = $db->query('SELECT foo FROM bar'); foreach ($result as $row)... Dec 24, 2009 at 19:49
  • 1
    Strictly speaking, it's not a PHP bottleneck, no, but it's something you're likely to encounter in PHP code. Dec 24, 2009 at 20:06
1

curl_exec() is very slow, compared to typical operations. Also, most str_* operations are faster than regex operations.

1
  • json_encode is faster than serialize
  • Concatenate in loop is faster than implode

People think that @ is expensive maybe only because this saying is quite wide-spread on the web.

quoting from : http://www.php.net/manual/en/language.operators.errorcontrol.php#102543

If you're wondering what the performance impact of using the @ operator is, consider this example. Here, the second script (using the @ operator) takes 1.75x as long to execute...almost double the time of the first script.

So while yes, there is some overhead, per iteration, we see that the @ operator added only .005 ms per call. Not reason enough, imho, to avoid using the @ operator.

real 0m7.617s user 0m6.788s sys 0m0.792s

vs

real 0m13.333s user 0m12.437s sys 0m0.836s

You can nearly unable to "overuse" an operator and it often worth if it is doing an operation you want.

0

foreach() statements, especially with nesting, are frequently expensive; though that's as much my naive -and occasionally poorly-planned- approach to programming as php's fault.

Though I think it's true, also, of JS and other languages, so almost certainly my fault. =/

1
  • Its not necessarily the foreach itself that is slow, but rather the logic within the foreach. Best practice there would be to loop over data once and only once, whenever possible, and to do as little processing inside a foreach loop as possible, since that loop will be run 1-infinity times, depending on the size of the set that you are iterating over.
    – JC.
    Dec 24, 2009 at 21:14
0

From my own experience the most expensive operation in real terms is the echo statement. Try and join all string together before outputting them to the browser, followed by database calls especially joins!

Code can also sometimes get a x10 performance increase by just simply refactoring your algorithms and data structures. Get any program and try to half its length, can you half it again?

2
  • So you mean assign everything you're going to echo to a variable and then echo that variable when ready? Dec 24, 2009 at 19:53
  • Think of it like this Darrell: echo "text1" echo "text2" echo "text3" is slow than echo "text1 + text2 + text3" It is also true in languages like Java and C# wherein you output a bunch of statements to the console.
    – Woot4Moo
    Dec 24, 2009 at 20:03
0

uniqid() is stupid expensive. Don't use to generate lots of unique identifiers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.