PHP Benchmarks

Performance comparison of PHP code alternatives.

Test: many classes vs. associative arrays

Does it make any difference when you have multiple classes being instantiated vs. multiple arrays? Note that both are wrapped in an eval to make it fair (another option would be to pre-create all of the classes, but this is more illustrative.)

View test history (6) Run this test again Return to test menu

Result: Discarded

The test labeled "classes" was the faster by 0.0879 seconds, (7.507% faster)

classes 100%
arrays 92.493%

The classes test took 1.0827 seconds.
The arrays test took 1.1706 seconds.

Nitty-Gritty

Each test case ran 20 random code order iterations consisting of 278,136 loops for a total of 5,562,720 runs.

  • Line execution difference (0.000016) milliseconds.
  • Avg difference (4.394) milliseconds per 278,136 loops.
  • Total difference 87.88 milliseconds for 5,562,720 loops

The iteration variablity for Code 1 was (2.7702) milliseconds and Code 2 was (4.4387) milliseconds. The lower and the closer together there values are the more accurate the results are.

Code

The first test, "classes", was:

$name = 'TestClass' . $GLOBALS['i']++;
eval('
class ' . $name . '
{
	var $x, $y, $z;
}

$data = new ' . $name . '();

$data->x = \'test\';
$data->y = 1;
$data->z = 5.5;');

The second test, "arrays", was:

$name = 'TestArray' . $GLOBALS['i']++;
eval('
$' . $name . ' = array(
	\'x\' => null,
	\'y\' => null,
	\'z\' => null,
);

$' . $name . '[\'x\'] = \'test\';
$' . $name . '[\'y\'] = 1;
$' . $name . '[\'z\'] = 5.5;');

Running: Linux (x86_64:1 GB) PHP (7.2.19-1+ubuntu16.04.1+deb.sury.org+1)