Everything I read about better PHP coding practices keeps saying don't use require_once
because of speed.
Why is this?
What is the proper/better way to do the same thing as require_once
? If it matters, I'm using PHP 5.
require_once
and include_once
both require that the system keeps a log of what's already been included/required. Every *_once
call means checking that log. So there's definitely some extra work being done there but enough to detriment the speed of the whole app?
... I really doubt it... Not unless you're on really old hardware or doing it a lot.
If you are doing thousands of *_once
, you could do the work yourself in a lighter fashion. For simple apps, just making sure you've only included it once should suffice but if you're still getting redefine errors, you could something like this:
if (!defined('MyIncludeName')) {
require('MyIncludeName');
define('MyIncludeName', 1);
}
I'll personally stick with the *_once
statements but on silly million-pass benchmark, you can see a difference between the two:
php hhvm
if defined 0.18587779998779 0.046600103378296
require_once 1.2219581604004 3.2908599376678
10-100× slower with require_once
and it's curious that require_once
is seemingly slower in hhvm
. Again, this is only relevant to your code if you're running *_once
thousands of times.
<?php // test.php
$LIMIT = 1000000;
$start = microtime(true);
for ($i=0; $i<$LIMIT; $i++)
if (!defined('include.php')) {
require('include.php');
define('include.php', 1);
}
$mid = microtime(true);
for ($i=0; $i<$LIMIT; $i++)
require_once('include.php');
$end = microtime(true);
printf("if defined\t%s\nrequire_once\t%s\n", $mid-$start, $end-$mid);
<?php // include.php
// do nothing.