note 91622 deleted from function.intval by danbrown
| From: | danbrown@php.net | Date: | Fri, 19 Jun 2009 21:45:20 +0000 |
| Subject: | note 91622 deleted from function.intval by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-157144@lists.php.net to get a copy of this message | ||
Note Submitter: alessandro at live dot it
----
intval() is a fundamental function, also for security purposes (it is perfect to prevent
SQL-injections etc)...
But...
This is astonishing!
Try this benchmark:
<?php
$result = array(1 => array(), 2 => array());
for($j = 0; $j < 5; $j++)
{
$id = 0;
$start = microtime(true);
for($i = 0; $i < 1000000; $i++)
{
$id = intval('222');
}
$end = microtime(true);
echo $end-$start;
echo "\n";
var_dump($id);
$result[1][] = $end-$start;
$id = 0;
$start = microtime(true);
for($i = 0; $i < 1000000; $i++)
{
$id = (int) '222';
}
$end = microtime(true);
echo $end-$start;
echo "\n";
var_dump($id);
$result[2][] = $end-$start;
}
echo "\n";
$avg[1] = array_sum($result[1]) / count($result[1]);
$avg[2] = array_sum($result[2]) / count($result[2]);
$min = min($avg);
echo "Test 1 avg: ".$avg[1];
echo "\n";
echo "Relative increment: ".((($avg[1] - $min) / $min) * 100)."%";
echo "\n\n";
echo "Test 2 avg: ".$avg[2];
echo "\n";
echo "Relative increment: ".((($avg[2] - $min) / $min) * 100)."%";
echo "\n\n";
?>
Result:
Test 1 avg: 0.51030764579773
Relative increment: 117.22726243067%
Test 2 avg: 0.23491878509521
Relative increment: 0%
That is! intval() is 117% SLOWER than using (int)!
They produce the same result, but the function takes at least twice the time...
Remember this when you write PHP code!