Performance of integer casting

Lessons learned:
  • $var+0 is as fast as (int)$var
  • intval($var) is 2 times slower than (int)$var
  • is_numeric($var) is 2 times slower than (int)$var
  • is_numeric($var) is 7 percent faster than intval($var)
  • settype($var) is 3 times slower than (int)$var

Here is the code:


<?php
test("10000a");
test("100000");

function test($i) {
$start = microtime(true);
for ($j=0; $j<1000000; $j++) $p = (int)$i;
echo number_format(microtime(true)-$start, 4)."\n"; // 0.1215, 0.0437

$start = microtime(true);
for ($j=0; $j<1000000; $j++) $p = $i*1;
echo number_format(microtime(true)-$start, 4)."\n"; // 0.0846, 0.0494

$start = microtime(true);
for ($j=0; $j<1000000; $j++) $p = $i+0;
echo number_format(microtime(true)-$start, 4)."\n"; // 0.0665, 0.0496

$start = microtime(true);
for ($j=0; $j<1000000; $j++) $p = intval($i);
echo number_format(microtime(true)-$start, 4)."\n"; // 0.1041, 0.0946

$start = microtime(true);
for ($j=0; $j<1000000; $j++) $p = doubleval($i);
echo number_format(microtime(true)-$start, 4)."\n"; // 0.0864, 0.0872

$start = microtime(true);
for ($j=0; $j<1000000; $j++) $p = is_numeric($i) ? $i : 0;
echo number_format(microtime(true)-$start, 4)."\n"; // 0.0953, 0.0887

$start = microtime(true);
for ($j=0; $j<1000000; $j++) $p = is_int($i) ? $i : 0;
echo number_format(microtime(true)-$start, 4)."\n"; // 0.0861, 0.0871

$start = microtime(true);
for ($j=0; $j<1000000; $j++) $p = is_double($i) ? $i : 0;
echo number_format(microtime(true)-$start, 4)."\n"; // 0.0870, 0.0859

$start = microtime(true);
for ($j=0; $j<1000000; $j++) $p = is_long($i) ? $i : 0;
echo number_format(microtime(true)-$start, 4)."\n"; // 0.0873, 0.0869

$start = microtime(true);
for ($j=0; $j<1000000; $j++) {
$p = $i;
settype($p, "int");
}
echo number_format(microtime(true)-$start, 4)."\n\n"; // 0.1446, 0.1440
}
Note: is_int("11") returns false, is_numeric("11") returns true.

Tests made with PHP 5.5.9 64bit, Xeon E3-1271 v3 @ 3.60GHz.

0 comments:

Post a Comment