dirname(__FILE__) vs __DIR__, which is faster?

or how __DIR__ is much better than dirname(__FILE__)

If you’re developing PHP software today but studied PHP based on old-ish manuals or manuals written by people who did, you might find a mix of calls to dirname(__FILE__) and __DIR__ and wonder what the difference is…

Past the fact that there is no real difference I could find in the data returned, it is interesting to note that __DIR__  is a MAGIC CONSTANT that exists in PHP since 5.3.0 and, as such, will certainly be faster most of the time. However, in the case of __DIR__, it is *always* faster, and considerably so.

Now, obviously, getting the current directory of the script will not be something that takes a very large chunk of the processing of your page, as you probably only call it once or twice at the beginning of your script (if calling it more than 2 times, it might make sense to just store it in a variable). However, when dealing with sites with millions of custom views (difficulting caching) every day, this might have some influence (I’m not saying it always will).

Anyway, here is a little table that I compiled to show the difference in load time. Somehow, loading the respective benchmarks in the same script in one order or another has a very small (but noticeable) influence in execution time, so I registered the change as well in the benchmark data. You can access this PHP __DIR__ vs dirname(__FILE__) benchmark here.

The impact of OpCache was not excessive either. That makes sense, considering the script itself is only ever executed once and I restart Apache after a config change to make sure they are taken into accoun. As such, OpCache doesn’t get a chance to warm up and cache an opcode version of the script.

Chart of execution time between dirname(__FILE__) and __DIR__ in PHP, showing 4 to 10 times efficiency improvement using __DIR__As such, although my benchmark (linked above) registers all these context changes, the results all go in the same direction,with the notable obvious data that ModPHP is definitely slower than CLI (probably because Apache intervenes each time in getting the path right), and the difference between __DIR__ and dirname(__FILE__) is smaller in this contect.

 

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on TumblrEmail this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *