PHP bench: require_once versus array_key_exists based require object
This a simple bench to see if require_once is the fastest solution to require a file only one time, versus a custom object using an internal array.
All tests, b.php:
<?php $GLOBALS['a']++; ?>
First test, a.php (require_once):
<?php $a = 1;
for ($i = 0; $i < 10000; $i++) { require_once 'b.php'; }
echo "$a "; ?>
Results:
real 0m3.640s user 0m0.308s sys 0m0.740s
Second test, a.php (array based custom require object):
<?php class myRequire { static private $files = array();
static public function load($file) { if (array_key_exists($file, self::$files)) { return true; }
require $file; self::$files[$file] = true; return true; } }
$a = 1;
for ($i = 0; $i < 10000; $i++) { myRequire::load('b.php'); }
echo "$a "; ?>
Results:
real 0m0.080s user 0m0.064s sys 0m0.016s
Yeah, require_once seems a bit slow after all, because it will open and do a fstat() on the file each time its called, even if the file has already been included.