Performance of ternary operator

Asked

Viewed 106 times

3

I recently came across an assignment to a boolean variable as follows:

bool varTeste = (varEntrada == 100) ? true : false;

I know this is the same as the code below:

bool varTeste = (varEntrada == 100);

The question is whether there is a difference in performance/processing or the ? true : false is just unnecessary?

  • 4

    Even if there is a small difference you would need to perform this operation millions of times to become relevant. Most of the time the clarity of the code is much more important than these details, try to choose the form that makes the code more readable and easy to understand

2 answers

4


Strictly speaking, this depends on the programming language in question, the compiler or interpreter used and perhaps the execution environment. But in practice, the answer is nay, because any modern compiler or interpreter is intelligent enough to optimize this, transforming both forms into the same internal data structure (and therefore they would be equivalent, which is almost the same as saying that the first form becomes the second). Obviously, that makes the ? true : false redundant and unnecessary, but the performance will be the same.

  • I did some performance tests here. I took into consideration the comment of Rodrigo Sidney making many validations and the difference was really imperceptible.

1

The ternary in this case would be unnecessary and redundant. Making an "x-ray" in the operator between parentheses would be like this:

bool varTeste = (true || false) ? true : false;

See that shows a redundancy. In terms of performance it would be imperceptible or null, just a little difference in terms of bytes. But as the intention is only to assign a simple value, true or false, in this case it would be better to use bool varTeste = varEntrada == 100; (the parenthesis is also unnecessary).

EDIT: By the way, excellent comment from Rodrigo Sidney.

Browser other questions tagged

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