PHP: require vs require_once

It has been observed that require_once is up to 4 times slower than require. Various figures and measurements can be found on Google, sometimes contradictory. Including a file multiple times is inherently not good, as the file is read and the code within it is parsed and executed.

Sooner or later when building PHP applications, the desire arises to store part of the code in a separate file. This way you gain both code readability and logical structure. A good question is how granularly to split things - and there is no single right answer here.

include("file.php") - a PHP command that includes the file file.php. This means that if the file file.php contains a function x(), it will be available and usable after this command is executed. If the file file.php is not found, a warning-level notification is shown - whereas if in such a case you need "the world to stop", use require.

The more complex the code, the greater the likelihood that existing functions will depend on other functions likely stored in other files. For such cases, PHP came up with the function include_once("file.php").

function A() {
  return 123;
}

require_once("file_A.php")
function B() {
  return A();
}

It has been observed that require_once is up to 4 times slower than require. Various figures and measurements can be found on Google, sometimes contradictory. Including a file multiple times is inherently not good, as the file is read and the code within it is parsed and executed.

http://lv.php.net/manual/en/function.require-once.php#62838
http://peter.mapledesign.co.uk/weblog/archives/writing-faster-php-code-1-require_once

Both processes can be sped up by using the absolute rather than relative path - i.e. require("/var/www/user1/file1.php") rather than require("../../file.php"). In small projects the difference may not be noticeable, as relative paths are cached:
http://us2.php.net/manual/en/ini.core.php#ini.realpath-cache-size


Alternatives?

1. Use include (or require) only once;
2. Use the __autoload() function;
3. class_exists('myClass') || require('path/to/myClass.class.php');
4. function_exists('functionInFile') && return; or class_exists('ClassInFile') && return;
5. @include("file.php");

The last one - error suppression - is a relatively time-consuming process, as is well known, but that is a topic for another article :)

http://www.techyouruniverse.com/software/php-performance-tip-require-versus-require_once

P.S. Did I mention that calling static methods is faster?

Share:
Rate: 0 (0)
Views: 619

comments



What are others reading?