views:

256

answers:

8

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?

+2  A: 

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)

Pascal MARTIN
A: 

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. =/

David Thomas
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
+2  A: 
 "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

valya
+1, I never knew that `"Hello $name"` was slower than `"Hello " . $name` =)
David Thomas
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.
fsb
neither do "@" or anything else. stop fearing features, fear your bad code
valya
@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.
Darrell Brogdon
and, if you care so much, you can use optimized structures from SPL - great point!
Mr-sk
+1  A: 

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)
{
}
Josh Davis
It's not a PHP's bottleneck
valya
I would think the second example would be slightly /more/ expensive since there is an assignment instruction.
Darrell Brogdon
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
@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)...`
Darrell Brogdon
Strictly speaking, it's not a PHP bottleneck, no, but it's something you're likely to encounter in PHP code.
Frank Farmer
+5  A: 

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.

Will Shaver
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.
Darrell Brogdon
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
+7  A: 
  • 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.
zombat
Exactly the kind of answer I'm looking for. Thanks @zombat!!
Darrell Brogdon
In my experience, cloning an object is cheaper than instantiating a new one.
Josh Davis
A: 

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?

yannis
So you mean assign everything you're going to echo to a variable and then echo that variable when ready?
Darrell Brogdon
Think of it like this Darrell:echo "text1"echo "text2"echo "text3"is slow thanecho "text1 + text2 + text3"It is also true in languages like Java and C# wherein you output a bunch of statements to the console.
Woot4Moo
+1  A: 

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

Mr-sk