22
Loading a class test
Posted by Technocrat | Posted in php | Posted on 22-08-2009
I wanted to find out what is the fastest way to load a class in PHP. So I took the different ways to do it and tested them using microtime. What I found was a little surprising.
Here is the setup:
Each file will use:
$time_start = microtime(true);
To start the timer and:
$time_end = microtime(true); $time = $time_end - $time_start; var_dump($time);
To stop the timer and give me the time it took to run the code.
For this test my class is VERY simple:
class Test {
function __construct() {
echo 'test';
}
public function make() {
echo 'test2';
}
}
To run my code I used:
$test = new Test(); $test->make();
All this will be in an index.php file.
My first test was to use a direct path to a file that contained the class (I found that include vs require was not a noticeable difference in time. However require_once or include_once was slower). So the code I used was:
include dirname(__FILE__).'/class.test.inc.php';
This came back with an average of: 0.0001089
My second test was to use the spl_autoload_register function. So for this test I used:
spl_autoload_register('loader');
function loader($class_name) {
switch ($class_name) {
case 'Test':
include dirname(__FILE__).'/class.test.inc.php';
break;
}
}
This came back with an average of: 0.0001218
Which is a bit slower than the first test. Really this isn’t a major difference in speed but it is slower.
My next test was to add the path to the include path using:
set_include_path(dirname(__FILE__).PATH_SEPARATOR.get_include_path()); include 'class.test.inc.php';
This came back with an average of: 0.0001239
So this is slower than the previous but again not a major difference.
My final test was to put the class in the file. This really had a surprising result.
This came back with an average of: 1.788139. WOW! That’s a big difference! This would be a noticeable difference to a user.
Very interesting. So it would seem that if you really want to have the quickest setup for your program it would seem that the direct path is by far the best. Putting a class into a file that uses it is not.

