Assuming PHP version >= 5.2, which is a better solution for managing includes:
require_once DEFPATH . 'config.inc.php';
or
if (!defined('FOOBAR')) require DEFPATH . 'config.inc.php';
or something entirely different?
Site does not use a front controller or autoloader. Typical number of files needed to be included is 3 – 8.
I’ve heard, here and elsewhere, that require_once adds overhead and does not play nice with caching. But I’ve also heard that a small number of require_once statements is OK in practice in later versions of PHP.
There must also be some overhead associated with checking if something is defined, but that may be less of an issue.
In general, which is the better practice and why?
Yes, require_once() comes with CPU and memory overhead, but not in any way significant to performance. In fact, it’s a very efficient operation because PHP just does one hashtable lookup to decide whether that file has already been parsed or not. Don’t give yourself any unnecessary headaches with hacks like your !defined(‘FOOBAR’) example, because it does the same thing only with less elegance.
What takes time during a PHP request is the file path lookup and then the subsequent parsing step. The amount of resources needed for the runtime to determine whether you’ve already parsed the file before is negligible.
There are a few things you can do to make your request run faster:
If you’re using a code cache or some kind of runtime optimizer, read the manual – they have different strategies that can actually hurt performance or introduce bugs depending on your code.
One final advice: beware premature optimization! Requests taking between 0 and 50 miliseconds on the server are practically not distinguishable on the user side.