Improve PHP file loading

I think you have already known that require/include is faster than require_once/include_one. But sometime, we also need the functionality of require_once but do not suffer from the performance tradeoff. So here is a better way to re-invent PHP implement.

function requireOnce($file)
{
static $dict=array();

if (!isset($dict[$file]))
{
require $file;
$dict[$file] = true;
}
}

The idea is very simple: PHP array access is faster than require_once/include_one checking, so we just keep an array to store for loaded file. But the implement is not completed yet because we can have array key conflict here, requireOnce('path/to/file.php') and requireOnce('/absolute/path/to/file') will yeild an error. I shift the idea a bit to avoid the conflict: when we use require_once or include_once the file will always be a definition file, ie: a class or functions, and these files can be identify in other way by class name or a custom label. So I change the implement again

function loadClass($cls,$file)
{
static $dict=array();

$cls = strtolower($cls);

if (!isset($dict[$cls]))
{
require $file;
$dict[$cls] = true;
}
}

So we don't have to worry about key conflict anymore. The most important thing is that requireOnce is seriously faster than require_once, and so does loadClass . Through loadClass is slower than require_once two times, but it's still faster than require_once. In my test, it was 10 times faster (this means requireOne is 20 times faster!). You can find my test script under the attachment section.

I should check the memory usage too, but i'm too tired now (it's 1am already) so I will come back to this later. If you have a chance to try this technique in your project, please share your experience to see if this real works :)

AttachmentSize
test-require.zip1.33 KB

Comments

Interesting idea. I have not checked your code but I did try something similar some weeks ago.

One thing you should check is variable scopes inside and outside the included file because the included file is within a function block. I'll try to remember what I was attempting to do so I can remember why I abandoned the idea.

It would be great to have a transparent way of including files most efficiently. I use include_once all the time. In several places and with many files. I suggest you to work on this function more!

Cheers.

I was aware the problem with variables inside the scopes, but I just simply ignore it because I aim to definition files (e.g file only contains class / function definition). If the file requires some variables to work, then you can use global operators, or better refactor the code in this file to a function or a method in a class. I recommend the second way. And if your file does output then it's really better to use a template engine, such as Twig: it's my choice now.

(copied from the email :P)

Add new comment