Benchmark: dirname(__FILE__) vs __DIR__ in PHP

dirname(__FILE__) and __DIR__ give exactly the same result in PHP, although one (__DIR__) is evaluated at compile-time, while the other (dirname(__FILE__)) has at least part of it (the function) evaluated at execution time.

Ever wondered what the difference is, in terms of efficiency, between the two? I’ve written a *very* simple script to try it out:

<?php
$loops = 100000000;
echo 'Testing dirname(__FILE__)' . PHP_EOL;
$start = time();
$dir = '';
for ($i = 0; $i < $loops; $i++) {
 $dir = dirname(__FILE__);
}
echo 'dirname(__FILE__) took ' . (time()-$start) . 's' . PHP_EOL;
$start = time();
$dir = '';
for ($i = 0; $i < $loops; $i++) {
 $dir = __DIR__;
}
echo '__DIR__ took ' . (time()-$start) . 's' . PHP_EOL;

So what it does is it executes both statements 100,000,000 times on my laptop, without any PHP caching enabled.

The results?

Testing dirname(__FILE__)
dirname(__FILE__) took 17s
__DIR__ took 4s

So __DIR__ is about 4 times faster, albeit only when you consider 100,000,000 executions (which is unlikely in most configurations).

However, it is common for a complex PHP application to require about 10,000 executions of functions to render one single page, so if you have about 1000 users, you’ll start saving a relevant amount of processing time.

It's only fair to share...Share on Facebook
Facebook
Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin
Share on Tumblr
Tumblr
Email this to someone
email

Leave a Reply

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