-2

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
Fabrizio
  • 3,734
  • 2
  • 29
  • 32
  • I would think (bool) because it is a single operation compared to `!!` – OneCricketeer Nov 24 '15 at 22:22
  • 1
    crazzzzzzzzy plan, go benchmark it –  Nov 24 '15 at 22:27
  • I was just editing the question to add the benchmark.. see my edit and you can see that it is pretty much inconclusive (runner multiple times and they are the same speed but doesn't make sense to me because `!!` should do two calls (?) and `(bool)` only one (?) ) – Fabrizio Nov 24 '15 at 22:30
  • I'am really sure that you can optimize a lot of other stuff in your code instead of a conversion from string to bool ;) – René Höhle Nov 24 '15 at 22:31
  • true, and I always do that, but this is similar to my other question: it is faster `in_array` or `isset` . I want to know to understand how it works in the backend – Fabrizio Nov 24 '15 at 22:32
  • Use the source, Luke. Maybe the assignment takes more time than the conversion? – clemens321 Nov 24 '15 at 22:35
  • backend- so read the source code, its available for your entertainment –  Nov 24 '15 at 22:35
  • don't you guys think that it will be interesting also for other people that do not understand C ? – Fabrizio Nov 24 '15 at 22:36
  • 3
    interesting - nope, nothing is less interesting to me than mircoptermisation. im payed to get shit done. –  Nov 24 '15 at 22:48

1 Answers1

4

(bool)$a means: take $a and cast it to boolean.

!!$a means: take $a, cast it to boolean if it isn't one already, then take the resulting value and flip it, then flip it again.

Not only is (bool) faster to execute (yes, I have benchmarked it; no, you won't notice any difference unless you have millions of such operations), but it's way faster to read. If you need to cast a type, just cast a type; don't use some "clever" hackiness that'll confuse the hell out of whoever has to read your code.

lafor
  • 12,472
  • 4
  • 32
  • 35