Skip to content

Instantly share code, notes, and snippets.

@dansimau
Created September 20, 2011 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dansimau/1228729 to your computer and use it in GitHub Desktop.
Save dansimau/1228729 to your computer and use it in GitHub Desktop.
Test scripts for comparing the performance of declaring and instantiating classes dynamically in PHP using eval versus including from files.
#!/bin/bash
mkdir $1 || exit
c=0;
while [ $c -lt $1 ]; do
cat <<EOF >"$1/Foo_$c.php"
<?php
Class Foo_$c
{
function __construct() {
return true;
}
}
?>
EOF
c=$(($c + 1))
done
<?php
// Set memory limit to unlimited
ini_set('memory_limit', '-1');
$t = $argv[1];
$start = microtime(true);
// Run the loop
for ($i = 0; $i < $t; $i++) {
// Generate class code for test. Note that there is a significant difference between having
// the construct with the return statement than without. We're testing with a return to
// simulate "some kind of processing" happening in the class instantiation.
$code = <<<EOF
Class Foo_$i
{
function __construct() {
return true;
}
}
EOF;
// This eval instantiates the class
eval($code);
// This eval adds some processing time to assign an instantiated class to a variable
$foo = eval("return new Foo_$i;");
}
$end = microtime(true);
echo "Iterations: " . $t . "\n";
echo "Time: " . round($end - $start, 3) . "s\n";
echo "Memory (real): " . round(memory_get_usage(true) / 1024 / 1024, 2) . "MB\n";
?>
<?php
// Set memory limit to unlimited
ini_set('memory_limit', '-1');
$t = $argv[1];
$start = microtime(true);
// Run the loop
for ($i = 0; $i < $t; $i++) {
// Include the class code
require_once "./" . $t . "/Foo_" . $i . ".php";
// This eval adds some processing time to assign an instantiated class to a variable
$foo = eval("return new Foo_$i;");
}
$end = microtime(true);
echo "Iterations: " . $t . "\n";
echo "Time: " . round($end - $start, 3) . "s\n";
echo "Memory (real): " . round(memory_get_usage(true) / 1024 / 1024, 2) . "MB\n";
?>
@dansimau
Copy link
Author

Sample results:

Declaring and instantiating 10,000 classes using eval:

$ php ./time-eval.php 10000
Iterations: 10000
Time: 0.262s
Memory (real): 22MB

Declaring 10,000 classes using require_once and instantiating them using eval (without APC):

$ php ./time-include.php 10000
Iterations: 10000
Time: 1.198s
Memory (real): 26.25MB

Declaring 10,000 classes using require_once and instantiating them using eval (with APC):

$ php ./time-include.php 10000
Iterations: 10000
Time: 1.474s
Memory (real): 26.25MB
$

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment