note 57413 deleted from function.eval by sniper
| From: | sniper@php.net | Date: | Thu, 29 Dec 2005 09:16:05 +0000 |
| Subject: | note 57413 deleted from function.eval by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-100922@lists.php.net to get a copy of this message | ||
Note Submitter: techbio.org
----
see: http://us2.php.net/manual/en/function.eval.php#51766
This nice suggestion about eval speed below made me curious about some code I have been using as a
shortcut, so I came up with a qad test to see what the difference between inline and eval code might
be with loops.
<?php
/*
The test code basically adds and subtracts 1 from $ref $n times.
*/
// straight PHP
function control($n)
{
$ref = 0;
while ($n-- > 0)
{
$ref += ($n % 2) ? 1 : -1;
}
return $ref;
}
// eval with return
function testEval($n)
{
$ref = 0;
while ($n-- > 0)
{
$ref += eval('return ($n % 2) ? 1 : -1;');
}
return $ref;
}
// eval with inline scalar assignment
function testEval1($n)
{
$ref = 0;
while ($n-- > 0)
{
eval('$ref += ($n % 2) ? 1 : -1;');
}
return $ref;
}
// eval with while loop inlined
function testEval2($n)
{
$ref = 0;
eval('while ($n-- > 0) { $ref += ($n % 2) ? 1 : -1; }');
return $ref;
}
// PHP4 hack to get a number from microtime()
function microseconds()
{
$microString = microtime();
$microArray = split(' ',$microString);
$microSeconds = doubleval($microArray[0]) + (intval($microArray[1]) % 1000);
return $microSeconds;
}
echo '<pre>';
// on a Pentium M 1.5GHz laptop--adjust at will
$n = 100000;
$t = array(); // timers
$t[] = microseconds();
control($n);
$t[] = microseconds();
testEval($n);
$t[] = microseconds();
testEval1($n);
$t[] = microseconds();
testEval2($n);
$t[] = microseconds();
$base = 0;
foreach ($t as $ti)
{
echo ($ti - $base).'<br />';
$base = $ti;
}
echo '</pre>';
?>
returns:
200.543225 // base time (modulo 1000 seconds)
0.081147 // time for control (straight PHP loop) -- control()
1.636144 // time for 'return from eval' -- testEval()
1.816688 // time for 'in eval assignment' -- testEval1()
0.079999 // time for 'loop inlined eval' -- testEval2()
Interestingly, and maybe temptingly, the eval'd loop performs slightly faster than the normal
PHP loop. This relationship is consistent across several runs. I'd be interested to know what
features of the interpreter lead to faster execution here. Perhaps recursive eval calls would lead
to the Holy Grail of 'zero execution time'.
Note also: Returns from eval are slightly faster than in-eval assignments.