mardi 21 février 2017

(PHP) Performance between if-else statement and ternary operator

I notice the ternary operator is inefficient than if-else statement in some situation.

  • When assign with a variable (function test1), performance between if and ternary are almost same.
  • When assign with a literal number (function test2), the ternary operator performs much bad than if statement.

I want to know the reason that cause the difference.

And an addtional question. Look at my test result at the bottom. It seems that "if(false)" is efficient than "if(true)", and "false ?:" is efficient than "true ?:". Why?

Test code:

$_bpt;

function BeginProfile($text = null)
{
    global $_bpt;
    if($text !== null)
        echo $text, ': ';
    $_bpt = microtime(true);
}

function EndProfile()
{
    global $_bpt;
    echo microtime(true) - $_bpt, PHP_EOL;
}

function test1($a, $b)
{
    echo '[test1] a: ', $a, ' b: ', $b, PHP_EOL;
    $r = null;
    $i = null;

    BeginProfile('if');
    for($i = 0; $i < 10000000; ++$i)
        if($a > $b)
            $r = $a;
        else
            $r = $b;
    EndProfile();

    BeginProfile('ternary');
    for($i = 0; $i < 10000000; ++$i)
        $r = $a > $b ? $a : $b;
    EndProfile();

    echo PHP_EOL;
}

function test2($a, $b)
{
    echo '[test2] a: ', $a, ' b: ', $b, PHP_EOL;
    $r = null;
    $i = null;

    BeginProfile('if');
    for($i = 0; $i < 10000000; ++$i)
        if($a > $b)
            $r = 1;
        else
            $r = -1;
    EndProfile();

    BeginProfile('ternary');
    for($i = 0; $i < 10000000; ++$i)
        $r = $a > $b ? 1 : -1;
    EndProfile();

    echo PHP_EOL;
}

test1(0, 1);
test1(1, 0);
test2(0, 1);
test2(1, 0);

Test result: (php 5.5.12 cli, windows 7)

[test1] a: 0 b: 1 if: 0.40560913085938 ternary: 0.47002696990967
[test1] a: 1 b: 0 if: 0.69283294677734 ternary: 0.65520095825195
[test2] a: 0 b: 1 if: 0.3744010925293 ternary: 0.5928008556366
[test2] a: 1 b: 0 if: 0.59280109405518 ternary: 0.71760106086731

Aucun commentaire:

Enregistrer un commentaire