This post originated from an RSS feed registered with PHP Buzz
by Alan Knowles.
Original Post: require_once, one optimization too many?
Feed Title: Smoking toooo much PHP
Feed URL: http://www.akbkhome.com/blog.php/RSS.xml
Feed Description: More than just a blog :)
I noticed a small thread on pear-dev about require_once, the concept that having require_once to lazy load files, is slowing things down seems to crop up every so often.
The crux of the issue appears to be the impression that lazy loading is slowing things down somehow, and that doing something like this may improve performance.
class_exists('PEAR') or require_once 'PEAR.php';
Or even worse, thinking about using __autoload magic..
In early versions of PHP4.3, and before, each require_once call had to do quite a bit of work to determine if a file had already been included.
It made the assumption that you might have changed the include path, and therefore, the file you where requesting might actually not have been loaded. So each call went through your every path in your include_path, made sure each part of the directory existed, and the tried to open the file, this resulted in quite a few stat calls (via realpath), as well as a few opens.
How much this was slowing things down was never really examined in detail, (although from what I remember Rasmus indicated that Y! had done a few patches to address this), but the existance of this patch and the general assumtion was that stat and open where relatively expensive made the situation sound kind of serious.
After considering the issue, a few of the core developers (Andi and Rasmus I think) added a stat cache feature. So rather than stat'ing the whole path on each require, it looked it up in a cache. The result can be seen by running this
As you would see from the output, what happens now is that the second call to require_once, calls open once on each possible location of the file (normally something like ./PEAR.php and /usr/share/pear/PEAR.php)
This should be pretty efficient, as long as you dont modify the path during the your php script (like move a directory or something).
However, as the discussion this week shows, this questionable performance issue still hasnt disappeared. So I got bored today and wondered what would be involved in making it even more efficient. (basically optimizing the second call to any [require|include]_once)
The idea being that assuming most people dont change the include path that often (probably only once when the app starts), then caching the strings that get sent to [require|include][_once] and testing them before doing any file operations could basically kill this kind of talk. The concept and code are simple enough that it shouldnt have too many knock on effects, and shouldnt use up too many resources to save a few open()'s..
The question is though, is if this is really an issue or just the impression of an issue....