I am trying to microptimize the code and I was wondering which is the faster to convert a variable into a boolean:
<?php
$a='test';
$result1 = !!$a;
$result2 = (bool)$a;
?>
I am not worry about code size, just about execution time.
some benchmark here, but it is very inconclusive (tried multiple times), so I am wondering what happens in the source code of PHP to see if they are handled differently:
<?php
$a = 'test';
for($c=0;$c<3;$c++){
$start = microtime(true);
for($i=0;$i<10000000;$i++){
$result = !!$a;
}
$end = microtime(true);
$delta = $end-$start;
echo '!!: '.$delta.'<br />';
}
$a = 'test';
for($c=0;$c<3;$c++){
$start = microtime(true);
for($i=0;$i<10000000;$i++){
$result = (bool)$a;
}
$end = microtime(true);
$delta = $end-$start;
echo '(bool): '.$delta.'<br />';
}
result
!!: 0.349671030045
!!: 0.362552021027
!!: 0.351779937744
(bool): 0.346690893173
(bool): 0.36114192009
(bool): 0.373970985413