views:

319

answers:

2

To put it simply i am a fairly new PHP coder and i was wondering if anyone could guide me towards the best ways to improve performance in code as well as stopping those pesky memory leaks, my host is one of those that doesn't have APC or the like installed so it would all have to be hand coded -_-

+1  A: 

I don't think ordinary memory leaks (like forgetting to dispose of objects or strings) are common in PHP, but resource leaks in general are. I've had issues with:

  • database connections -- you should really call pg_close/mysql_close/etc. when you're done with the connection. Though I think PHPs connection pooling mitigates this (but can have problems of its own).

  • Images -- if you use the gd2 extension to open or create images, you need to image_destroy these, because otherwise they'll occupy memory forever. And images tend to be big in terms of data size.

Note that if your scripts run as pure CGI (no HTTP server modules), then the resources will effectively be cleaned up when the script exits. However there may still be memory issues during the script's runtime, especially in the case of images where it's not uncommon to perform many manipulations in a single script execution.

Edmund
A: 

In general, php scripts can't leak memory. The php runtime manages all memory for its scripts. The script itself may leak memory, but this will be reclaimed when the php process ends. Since php is mainly used for processing http-requests and these generally run for a very short time, this makes it a non-issue if you leak a bit of memory underway. So memory leaks should only really concern you if you use php for non-http tasks. Performance should be a bigger concern for you than memory usage. Use a tool such as xdebug to profile your code.

troelskn
as much as i would love to use xdebug i did mention that my host doesn't allow extra's installed but thank you :)
Marc Towler
I wouldn't install xdebug on a production environment. Install it on your developer machine.
troelskn
I'm observing a leak in my process where the memory doesn't get reclaimed after the script exits. PHP, of course, is to blame most likely.
Artem Russakovskii
@Artem: It's much more likely that the leak happens in an extension or in a linked library. You should try to isolate the bug and then disable extension one by one, to find the culprit.
troelskn