Performance of integer casting
Lessons learned:
- $var+0 is as fast as (int)$var
- intval($var) is 2.5 times slower than (int)$var
- is_numeric($var) is 3 times slower than (int)$var
- is_numeric($var) is 7 percent slower than intval($var)
- settype($var) is 40 percent slower than is_numeric($var)
Here is the code:
Note: is_int("11") returns false, is_numeric("11") returns true.
test("10000a");
test("100000");
function test($i) {
$start = microtime(true);
for ($i=0; $i<1000000; $i++) $p = (int)$i;
echo (microtime(true)-$start)."\n"; // 0.0435, 0.0440
$start = microtime(true);
for ($i=0; $i<1000000; $i++) $p = $i*1;
echo (microtime(true)-$start)."\n"; // 0.0481, 0.0487
$start = microtime(true);
for ($i=0; $i<1000000; $i++) $p = $i+0;
echo (microtime(true)-$start)."\n"; // 0.0439, 0.0449
$start = microtime(true);
for ($i=0; $i<1000000; $i++) $p = intval($i);
echo (microtime(true)-$start)."\n"; // 0.1173, 0.1196
$start = microtime(true);
for ($i=0; $i<1000000; $i++) $p = doubleval($i);
echo (microtime(true)-$start)."\n"; // 0.1188, 0.1166
$start = microtime(true);
for ($i=0; $i<1000000; $i++) $p = is_numeric($i) ? $i : 0;
echo (microtime(true)-$start)."\n"; // 0.1265, 0.1246
$start = microtime(true);
for ($i=0; $i<1000000; $i++) $p = is_int($i) ? $i : 0;
echo (microtime(true)-$start)."\n"; // 0.1272, 0.1265
$start = microtime(true);
for ($i=0; $i<1000000; $i++) $p = is_double($i) ? $i : 0;
echo (microtime(true)-$start)."\n"; // 0.1200, 0.1199
$start = microtime(true);
for ($i=0; $i<1000000; $i++) $p = is_long($i) ? $i : 0;
echo (microtime(true)-$start)."\n"; // 0.1267, 0.1258
$start = microtime(true);
for ($i=0; $i<1000000; $i++) {
$p = $i;
settype($p, "int");
}
echo (microtime(true)-$start)."\n\n"; // 0.2115, 0.2109
}
Comments
Post a Comment