1 August 2006
Eval Preformance
I’ve always assumed implicit evaluation was faster than eval, but today, I finally tested that. Eval is four times slower than implicit evaluation.
// Eval Sample
$var = 1;
for ($x = 0; $x < 100000; $x++) {
eval ("$w$var=$var++;");
}
// Implicit Sample
$var = 1;
for ($x = 0; $x < 100000; $x++) {
$strVar = 'w' . $var;
$$strVar = $var++;
}
Each sample was ran independently. The first sample (eval) took roughly 1.3s to run. The second (implicit evaluation) took roughly 0.3s. Of course, you’ll want to run it on your own machine/server to find the delta for your own purposes, but the 4x penalty should hold pretty constant.
Eval has many things stacked against it. For one, each call effectively forks PHP. Even though the environment remains the same, each call to eval must be re-interpretted and re-parsed. In implicit evaluation, there is no repeated parsing. The implicit example also has the advantage of being much more clear in terms of what its doing.
So go forth and use implicit evaluation. There are times you must use eval, particularly when writing templating code. But most uses of eval are entirely unneccessary. Write your dynamic code statically. Evaluate variables instead of entire strings. Its easier to write, faster to run, and easier to understand. There is no downside.

