Is there any performance gain when using ternary operator instead of a conditional operator?

Asked

Viewed 1,055 times

13

What is the difference in performance using conditional operators and ternary operators? Is there any significant gain or the choice of use of ternary operators is unique to code simplification?

Code example with conditional operator:

var x;

if ($foo) {
    x = "John Doe";
} else {
    x = "Foo";
}

Example of ternary operator code:

var x = $foo ? "John Doe" : "Foo";
  • Is there anything I can improve on the answer, or the others?

  • 2

    Hello @qmechanik, all the answers are very enlightening and detailed, I left a time without schedule to ensure that there was no one else to add something or not to "choose too fast" as I’ve been seeing on meta.

  • Are you doing any study or are performing performance adjustments on any real web application?

  • Hello @Intruder, I’m finalizing the development of my TCC this year, I did not have the habit of using ternary operators and now that I’m starting I have arisen the question of whether my gain was only in readability or in something more.

  • This type of optimization is usually not done in most applications because in the web, the cost elsewhere is actually more significant. You can take a look at this guy’s material to better understand what I’m talking about: https://www.stevesouders.com/

3 answers

13


Importance of performance

PHP is a language where performance is not important, it is slow in much of its operations. So keep in mind that all information here is only relevant as curiosity. The cost of processing one or the other is very low for everything you want to do with PHP. If you need more performance yet, another language should be used.

Validity of performance tests

Also by way of curiosity, can be seen another answer that I posted about C#. Ali shows that in that language the code of the two forms produce the same bytecode (intermediate code) and must produce the same native code. So there is no difference in performance. So each situation is different.

In PHP it could happen exactly the same thing, but it doesn’t happen.

Note that although some pseudo programmers find it possible to compare performance of programming languages or even different mechanisms of the same language, this is not possible. You can even joke, but you can’t do serious conclusive studies. Some more conscious will even say that you cannot compare languages because they are abstract and have different versions. Then it would be possible to compare implementations which is something more concrete. Nor is this possible.

Even comparing hypothetical situations should be considered with a pinch of salt. You can compare real algorithms used in real situations. Then I’ll go compare algorithms and not exactly the conditional operator versus the conditional command. I will compare a broader processing using these mechanisms. Nor is it possible to compare only them. I will compare something that does much more than these operations.

It is also good to realize that I will run the test in an environment that is not ideal. Other factors may influence the result running on ideone. In addition what works well running on one machine can run differently on another. I don’t think this will happen with this test in PHP, but remember this in any benchmark what to see. This is one more reason that prevents us from trusting in these tests.

The test

See the test on ideone. And in the repl it.. Also put on the Github for future reference.

Run a few times to see that gives difference.

$inicio = microtime(true);
for ($i = 0; $i < 10000; $i++) {
    $var = $i;
}
echo (microtime(true) - $inicio) * 1000 . "\n";

$inicio = microtime(true);
for ($i = 0; $i < 10000; $i++) {
    $var = $i == 500 ? 0 : $i;
}
echo (microtime(true) - $inicio) * 1000 . "\n";

$inicio = microtime(true);
for ($i = 0; $i < 10000; $i++) {
    if ($i == 500) {
        $var =  0;
    } else {
        $var = $i;
    }
}
echo (microtime(true) - $inicio) * 1000 . "\n";

Note that what really takes time is other things. It is the control of the loop with all the necessary operations in it - increment, comparison, decision and deviation - in addition to the expense of assigning a value to the variable.

I don’t know what optimizations PHP does and it may be that this test isn’t even ideal. I don’t think it does any relevant optimization. I’ve done some previous tests to try to figure out if there’s any optimization that would harm the test unduly, but there doesn’t seem to be. I could be wrong. If anyone can give information to help improve the test, it would help everyone. But I know that no test will be perfect. In theory we can create a perfect test but it is very difficult to meet all the conditions.

The first loop only executes the repetitions and does a normal assignment to know how long it takes to do this. The second obviously uses the conditional and the third can see that uses the if.

It is not curious that the if was faster? Note that you can notice that the use of if increases the total processing time by about 2 tenths. It may vary when you have it executed. And the ternary increases by 2 tenths. So we can roughly conclude that the ternary takes twice as long as the if. But it’s not the time necessarily spent on the mechanism itself, it’s a measurement of the processing of this part of the algorithm.

Test relevance

But keep in mind that this is how it was used. Otherwise it could give another completely different result. Even so, have you noticed how this operation spends little time compared to all processing? The loop and assignment consume 10 times more time. At least that’s how it is in this version of PHP, on this computer.

I came up with a test running more than a simple variable assignment, something heavier, but not too heavy - something that would normally occur in real situation. The difference from one algorithm to another that in the test demonstrated is already in the range of 10%, dropped to less than 1%.

Notice how it’s not usually relevant? In real processing running on production systems, this difference is usually lower.

The execution of each of these operations took about 20 to 40 microseconds. It’s very little. Of course, compared to other native code languages that can do the same in the nanosecond house, this is tragic. But it’s good enough for PHP.

Completion

There is a clear gain from the conditional command in this situation. But I do not guarantee that it occurs at all. It is probable, but not guaranteed. The gain is small, especially if you consider it in a larger processing, which is the case with virtually any real code. The gain is so small that if it makes a difference in what your software needs, PHP is the wrong language.

Then the choice must fall on which is more readable, which better passes the intention. Remembering that short code is usually more readable, until it gets too crowded, then the size starts playing against. Short code should not be the goal, clarity and expressiveness, yes. Performance comes well after.

Only reinforcing that this test cannot be considered valid even between different versions of PHP, much less for other languages.

  • Of course it’s in case of performance.

  • Anyway, I participated in a very serious study comparing an image analysis algorithm between languages and it was possible to determine which language had the performance necessary for that function. After the study we had to introduce another language in the project to take care of that particular resource, by performance requirement. None of those involved were pseudo-programmers.

  • para aquela função was the secret. And even if you take the same study and apply years later with the same languages but with their more modern versions on more modern computers, the result will not be the same. It is possible until it does not invalidate the study but decreases its relevance. I have no data about it to talk about. I can only talk about what I know. There is no room here to go into detail on the subject. If you know the subject well you know what I am talking about. If you do not know we will be debating unproductively.

  • Ok, with your comment I understood your point that I had not understood before just reading the answer.

  • Good evening, I really didn’t get it: PHP is a language where performance is not important. Do you mean the operators or do you mean something else? The phrase sounds strange, could you explain?

  • No, I mean everything, nobody chooses this language because it is fast. Could you explain why it sounds strange? Who knows then I could clarify.

  • 1

    Why didn’t you use the @usuario I hadn’t seen your message, OK, for me at least it sounds like in "PHP performance doesn’t matter," it sounds like I did something in PHP and it didn’t have a performance problem, or in PHP it might be slow. I don’t mean that’s what you meant, but it sure sounds like something else for most of you to read, of course it’s up to you to believe what I say or not. Usually when we write of our understanding, we hardly take into account the understanding that sounds to others, this is human.

  • @Guilhermenascimento can be, then I give a review, although the idea is +/- this same. Apart from committing big absurdities, making something quadratic that can be linear, or things like that, it is no use wanting to optimize things a lot in PHP, it will hardly have a relevant effect. So I’ll put something to make it clear that PHP is really slow.

  • 1

    Now I understand, although I disagree, I want to say: maybe in matters of server Apis, etc., we can say that it really has nothing to improve, but in a matter of how it is programmed by the user, I believe that this becomes wrong information, but it is just my opinion. Grateful and a good holiday for you.

Show 4 more comments

7

Both are equal, neither is better than the other, if there is any difference, she is insignificant, the only advantage of a ternary operation is readability and a code more clean.

Using one or the other will depend on the context, in a situation where it is necessary to execute several instructions, the if {..} else {..} is preferable, when it is to execute a single instruction, for example, assign a value to a variable, it is possible use the ternary.

Situation where the if/else is appropriate:

if ($foo){
  instrucao1()
  instrucao2()
  instrucaoN()
} else {
  outraInstrucao1()
  outraInstrucao2()
  outraInstrucaoN()
}

Situation where the ternary operator is appropriate:

$x = $foo ? "Foo" : "John Doe";

From the PHP 5.3 it is possible to use the ternary shortcut ?::

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. The Expression Expr1 :? Expr3 return Expr1 if Expr1 is assessed as True, or Expr3 otherwise.

Example:

$foo = "Foo";
$x = $foo ?: "John Doe";

7

Disambiguation

The ternary operator as it is called is a conditional operator, commonly known as ternary operator as part of the ternary operator group (3 operands).

Both make use of a condition by evaluating it for a boolean result that will allow them to proceed with logic.

Who’s faster

In the case of the conditional operator ?:, the same is but an expression that operates on the basis of a conditional motion cmov.

The conditional operator if~else operates at the base of a tree branches.

This difference in operation, coming from c/c++, the PHP implementation languages, a few years ago could make some difference, where the conditional operator ?: was ahead in terms of performance.

Nowadays, the difference is imperceptible and the comparison between the two futile.

And then, which to use?

?: is more practical in:

  • Simple checks:

    $sair = ($resposta=="sim");
    
  • Checks inline:

    echo "Olá" . (isLogged() ? $user->name : "Convidado");
    
  • Initialize variables:

    $bubu = ("chocolate"=="bom") ? 'sem fome' : 'com fome';
    

if~else is more practical in:

  • Complex checks:

    if (isLogged() && accessRights()!=4 && "bubu"=="com fome") {
       $mensagem = "Vamos lá" . groupName();
    }
    else {
        $mensagem = "Ninguém vai a lado nenhum!";
    }
    
  • Multiple checks:

    if ($bubu=="cheio") {
        $mensagem = "Parar de comer";
    }
    else if ($bubu=="assim assim") {
        $mensagem = "Comer mais um pouco!";
    }
    else {
        $mensagem = "Enfardar até cair pró lado!";
    }
    

In short the advantage lies more on the programmer’s side and in the ease of making the code readable as well as keeping it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.