include() vs. Functions

A while ago, I had an intriguing conversation with somebody who disclosed some secrets about PHP. He told me that he does not use functions but rather include files, since a function file would have to be included and since something has to be included anyway, there was no need for the function after all.

I always thought that a function is cleaner than an include file which inherits all your variables and changes them without you noticing by chance. A function is encapsulated so that this would not happen. Recursion should be out of the question with include files, or at least it seems very cumbersome to me.

Anyway, one of the things that I learned from Steve McConnel's books is that you should not "optimize" something unless you can show that it is really faster or better than before. In order to be fair, I put together a little test case for the claim regarding include files.

It basically has a very simple code snipped that I wrapped up into a simple include file foo.php, a similar snippet that I wrapped up in a function (foo2.php). Then there is the test.php which does the magic.


# Copyright (c) 2011 Martin Ueding <>

$count = 10000;

# Start with including the code snippet $count times.
$start = microtime(true);
for ($i = 0; $i < $count; ++$i) {
$duration_include = microtime(true)-$start;
# End include part.

# ------------------------------------------------------

# Begin function part.
$middle = microtime(true);

# Define the function.

# Call the function.
$second = microtime(true);
for ($i = 0; $i < $count; ++$i) {

$duration_function = microtime(true)-$second;
$duration_function_and_require = microtime(true)-$middle;
# End function part.

# ------------------------------------------------------

# Print the report.
print "include:\t\t".$duration_include."s\n";
print "function:\t\t".$duration_function."s\n";
print "function+require_once:\t".$duration_function_and_require."s\n";
print "\n";
print "The include method is ".($duration_function_and_require/$duration_include)." times faster than defining a function and using it $count times.\n";
print "The function method is ".($duration_include/$duration_function_and_require)." times faster than including the same code $count times.\n";


$k = 1;
$y = 2*$k;


function foo($i) {
    $y = 2*$i;


This is what my machine came up with:

Method Time
include 0.3787100315094
function 0.026961803436279
function+require_once 0.027056932449341

The include method is 0.071 times faster. The function method is 14 times faster.