Ternary operator performance

3

Recently I 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 performance / processing difference exists or does ? true : false just be unnecessary?

    
asked by anonymous 23.02.2018 / 15:29

2 answers

3

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

    
23.02.2018 / 15:32
1

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

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

See that it shows a redundancy. In terms of performance would be inconspicuous or null, just a little difference in terms of bytes . But as the intent is just to assign a simple value, true or false , in this case it would be best to use bool varTeste = varEntrada == 100;

EDIT: By the way, excellent review of the Rodrigo Sidney .

    
23.02.2018 / 15:51