14 Answers
14

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:

I doubt your defined() method is any faster than the built-in lookup table, but I agree with your overall point - surely a non-issue?!
– Bobby JackOct 9 '08 at 8:42

1

I'm fairly sure you're right Bobby but I'm not advocating the defines over _once. It's just an option. The time it would take to interpret the code might even make it marginally slower but, that said, I don't know how thorough the internal method is. It might do extra work to ensure no duplicates.
– OliOct 9 '08 at 9:37

I just did a very basic test of the two methods -- I did 1,000,000 iterations including a file which simply defined a constant 'testinclude' to true. In the first test, I used require_once, the second I used if(!defined('testinclude')) and the results were interesting: Require: 0.81639003753662 Not Defined: 0.17906713485718 Defined is 0.63732290267944 microseconds faster.
– Travis WestonJun 26 '14 at 19:35

The case with define will be faster since you're not performing any kind of extra checks such as using realpath. It's not comparing two things that are truly the same.
– jgmjgmJul 11 '17 at 15:07

This thread makes me cringe, because there's already been a "solution posted", and it's, for all intents and purposes, wrong. Let's enumerate:

Defines are really expensive in PHP. You can look it up or test it yourself, but the only efficient way of defining a global constant in PHP is via an extension. (Class constants are actually pretty decent performance wise, but this is a moot point, because of 2)

If you are using require_once() appropriately, that is, for inclusion of classes, you don't even need a define; just check if class_exists('Classname'). If the file you are including contains code, i.e. you're using it in the procedural fashion, there is absolutely no reason that require_once() should be necessary for you; each time you include the file you presume to be making a subroutine call.

So for a while, a lot of people did use the class_exists() method for their inclusions. I don't like it because it's fugly, but they had good reason to: require_once() was pretty inefficient before some of the more recent versions of PHP. But that's been fixed, and it is my contention that the extra bytecode you'd have to compile for the conditional, and the extra method call, would by far overweigh any internal hashtable check.

Now, an admission: this stuff is tough to test for, because it accounts for so little of the execution time.

Here is the question you should be thinking about: includes, as a general rule, are expensive in PHP, because every time the interpreter hits one it has to switch back into parse mode, generate the opcodes, and then jump back. If you have a 100+ includes, this will definitely have a performance impact. The reason why using or not using require_once is such an important question is because it makes life difficult for opcode caches. An explanation for this can be found here, but what this boils down to is that:

If during parse time, you know exactly what include files you will need for the entire life of the request, require() those at the very beginning and the opcode cache will handle everything else for you.

If you are not running an opcode cache, you're in a hard place. Inlining all of your includes into one file (don't do this during development, only in production) can certainly help parse time, but it's a pain to do, and also, you need to know exactly what you'll be including during the request.

Autoload is very convenient, but slow, for the reason that the autoload logic has to be run every time an include is done. In practice, I've found that autoloading several specialized files for one request does not cause too much of a problem, but you should not be autoloading all of the files you will need.

If you have maybe 10 includes (this is a very back of the envelope calculation), all this wanking is not worth it: just optimize your database queries or something.

This is 4 years old and for the most part no longer applies, define(), require_once() and defined() all take about 1-2 microseconds each on my machine.
– Daniel BeardsleyAug 8 '12 at 22:47

69

But that's 2 microseconds sooner the user would have the page. Over a year of page views, that could save the user a whole 3 seconds! They could watch one tenth of a commercial in that time! Think of the user. Don't waste microseconds.
– Andrew EnsleyOct 1 '12 at 18:42

14

Just so everyone is aware of the sarcasm, a microsecond is 1/1000000 of a second.
– andychaseApr 3 '13 at 21:14

class_exists('Classname') checks if a class name has been included while require_once() checks that a file has been included, keep in mind that multiple files can contain the same class.
– Timo HuovinenDec 13 '13 at 13:39

@AndrewEnsley You are simply mistaken with all your sarcasm. You are ignorant about the fact that PHP also runs on microprocessors, 1 microsecond on your PC is several milliseconds on a microprocessor. Now what about having 20 include files, a larger project ? That's 20 times several milliseconds delay introduced, so we are already reaching a point thats noticeable to a human. If that script is called frequently it will cause performance issues on the system. Optimization is not a joke and the whole world is not turning around your PC. There are ten thousands of CPUs in use.
– JohnOct 9 '17 at 18:32

I got curious and checked out Adam Backstrom's link to Tech Your Universe. This article describes one of the reasons that require should be used instead of require_once. However, their claims didn't hold up to my analysis. I'd be interested in seeing where I may have misanalysed the solution. I used php 5.2.0 for comparisons.

I started out by creating 100 header files that used require_once to include another header file. Each of these files looked something like:

I didn't find much difference when running this with require vs. require_once. In fact my initial tests seemed to imply that require_once was slightly faster, but I don't necessarily believe that. I repeated the experiment with 10000 input files. Here I did see a consistent difference. I ran the test multiple times, the results are close but using require_once uses on average 30.8 user jiffies and 72.6 system jiffies; using require uses on average 39.4 user jiffies and 72.0 system jiffies. Therefore, it appears that the load is slightly lower using require_once. However, wall clock is slightly increased. The 10,000 require_once calls use 10.15 seconds to complete on average and 10,000 require calls use 9.84 seconds on average.

Next step is to look into these differences. I used strace to analyse the system calls that are being made.

Before opening a file from require_once the following system calls are made:

Tech Your Universe implies that require_once should make more lstat64 calls. However, they both make the same number of lstat64 calls. Possibly, the difference is that I am not running APC to optimize the code above. However, the next thing I did was compare the output of strace for the entire runs:

This seems to imply that you could reduce the number of system calls by using absolute paths rather than relative paths. The only difference outside of that is the time(NULL) calls which appear to be used for instrumenting the code to compare what is faster.

One other note is that the APC optimization package has an option called "apc.include_once_override" that claims that it reduces the number of system calls made by the require_once and include_once calls (see the PHP docs).

And any "optimization" that you have to run 10,000 times to see a such a minuscule difference is not even worthy of worrying about. Use a profiler and find out where the real bottlenecks are in your application. I doubt this question is the bottleneck.
– DGMMar 27 '09 at 23:53

Can you give us any links to these coding practices which say to avoid it? As far as I'm concerned, it's a complete non-issue. I haven't looked at the source code myself, but I'd imagine that the only difference between include and include_once is that include_once adds that filename to an array and checks over the array each time. It'd be easy to keep that array sorted, so searching over it should be O(log n), and even a medium-largish application would only have a couple of dozen includes.

one is, chazzuka.com/blog/?p=163 they really didnt 'not to', but too many 'expensive' things add up. and actually, all included/required files are added to an internal array (theres a function to return it), i guess the _once's have to loop that array and do strcmp's, which would add up
– UberfuzzyOct 9 '08 at 8:46

1

Actually, it also has to resolve symlinks.
– John LindalDec 8 '12 at 17:33

but the very first example in the autoloading objects page you linked to uses require_once
– ShabbyrobeOct 9 '08 at 8:13

I think require would work there too (not tested though)
– GregOct 9 '08 at 8:24

I don't buy this. There are MANY situations in which OO does not fit as appropriately as other paradigms, so you shouldn't force it just to gain whatever tiny advantages there may be with __autoload().
– Bobby JackOct 9 '08 at 8:40

1

you'd think that autoload would actually take longer than *_once (assuming that you're only require'ing what you need).
– nickfOct 10 '08 at 0:19

No it is not, at least not definitely, Autoload still needs to be included somehow and it is a last resort for PHP before error fail - so in reality PHP actually perform potentionally unnecessary checks through all places that would apply to include/require and AFTER THAT it would call autoload (if any defined)... PS: __autoload() is discouraged and it may be deprecated in the future, you should use spl_autoload_register(...) these days... PS2: don't get me wrong, I do use autoload functionality sometimes ;)
– jave.webApr 28 '16 at 21:33

Thanks for the pointer to the article. require_once() is a good safety belt over double-including files, and we'll continue to use it, but being able to make it clean is nice.
– Andy LesterOct 12 '08 at 1:48

Update: As the web archived version of the wiki is eye-gougingly ugly, I've copied the most compelling reasons below:

include_path is required in order to use a (PEAR) package. This makes it difficult to bundle a PEAR package within another application with its
own include_path, to create a single file containing needed classes,
to move a PEAR package to a phar archive without extensive source code
modification.

when top-level require_once is mixed with conditional require_once, this can result in code that is uncacheable by opcode caches such as
APC, which will be bundled with PHP 6.

relative require_once requires that include_path already be set up to the correct value, making it impossible to use a package without
proper include_path

It's not using the function that is bad. It's an incorrect understanding of how and when to use it, in an overall code base. I'll just add a bit more context to that possibly misunderstood notion:

People shouldn't think that require_once is a slow function. You have to include your code one way or another. require_once() vs. require()'s speed isn't the issue. It's about the performance hindering caveats that may results for using it blindly. If used broadly without consideration for context, it can lead to huge memory waste or wasteful code.

What I have seen that's really bad, is when huge monolithic frameworks use require_once() in all the wrong ways, especially in a complex Object Oriented environment.

Take the example of using require_once() at the top of every class as seen in many libraries:

So the User class is designed to use all 3 other classes. Fair enough!
But now what if a visitor is browsing the site and not even logged in and the framework loads: require_once("includes/user.php"); for every single request.

It's including 1+3 unnecessary classes it won't ever use during that particular request. This is how bloated frameworks end up using 40MB per request as opposed to 5MB or less.

The other ways it can be misused, is when a class is re-used by many others!
Say you have about 50 classes that use helper functions. To make sure helpers are available for those classes when they are loaded, you get:

The use of require_once() technically affects performance for running that function 14 times, on top of having to parse those unnecessary lines. With just 10 other highly used classes with that similar problem, it could account for 100+ lines of such rather pointless repetitive code.

With that, it's probably worth using require("includes/helpers.php"); at the bootstrap of your app or framework, instead. But since everything is relative, it all depends if the weight versus usage frequency of the helpers class is worth saving 15-100 lines of require_once(). But if the probability of not using the helpers file on any given request is none, then require should definitely be in your main class instead. Having require_once in each class separately becomes a waste of resources.

The require_once function is useful when necessary, but it shouldn't be regarded as a monolithic solution to use everywhere for loading all classes.

Even if require_once and include_onceare slower than require and include (or whatever alternatives might exist), we're talking about the smallest level of micro-optimization here. Your time is much better spent optimizing that poorly written loop or database query than worrying about something like require_once.

Now, one could make an argument saying that require_once allows for poor coding practices because you don't need to pay attention to keeping your includes clean and organized, but that has nothing to do with the function itself and especially not its speed.

Obviously, autoloading is better for the sake of code cleanliness and ease of maintenance, but I want to make it clear that this has nothing to do with speed.

Yes, it is slightly more expensive than plain ol' require(). I think the point is if you can keep your code organized enough to not douplicate includes, don't use the *_once() functions, as it will save you some cycles.

But using the _once() functions isn't going to kill your app. Basically, just don't use it as an excuse to not have to organize your includes. In some cases, using it is still unavoidable, and it's not a big deal.

If require_once() fails, your script is done. Nothing else is processed. If you use include_once() the rest of your script will try to continue to render, so your users potentially would be none-the-wiser to something that has failed in your script.

Not necessarily. You can actually hook in an error handler or on shutdown handler to give the user a nice error page (although people rarely do). As a developer, I would much rather things error immediately.
– Edward Z. YangOct 12 '08 at 2:13

1

Or, as the case may be, not failing gracefully - if some vital file isn't require()'d properly, it's a good idea just to give up and halt. But that's require vs include, whereas I think the question is more focused on require vs require_once.
– HoboBenOct 12 '08 at 14:36

My personal opinion is that the usage of require_once (or include_once) is bad practice because require_once checks for you if you already included that file and suppress errors of double included files resulting in fatal errors (like duplicate declaration of functions/classes/etc.).