Rudolf Adamkovič
Rudolf Adamkovič

Reputation: 31486

Does using ?: to do an assignment produce faster assembly than using if()?

I'd like to know which one of the following two forms of lazy instantiation generates faster assembly code. Here's the code:

1st:

if (!_separatorTopBorderColor) _separatorTopBorderColor = UIColorFromHex(0x393A3B);
return _separatorTopBorderColor;

2nd:

_separatorTopBorderColor = _separatorTopBorderColor ?: UIColorFromHex(0x393A3B);
return _separatorTopBorderColor;

Upvotes: 2

Views: 219

Answers (4)

Vishal
Vishal

Reputation: 2181

It might be an issue 10 years ago, but nowadays, compilers literally sees any difference with ternary operators and if-else statements. My advise is that you should concentrate on keeping your code more readable, maintainable, and efficient. Don't care about resource or memory usage in this case.

Upvotes: 1

janneb
janneb

Reputation: 37198

Well, choose whichever is more readable.

Now, from a compiler optimization perspective, most optimizing compilers contain an optimizer pass called "if-conversion" or something like that, which is a pass which can convert a SIMPLE branch into a conditional move instruction. In your case you have a function call right there in one of the branches, so this doesn't matter. Secondly, on a superscalar OoO processor with decent branch prediction, conditional moves are in most cases a pessimization compared to a simple branch, so in fact compilers targeting such CPU's will most likely not do the if-conversion.

Upvotes: 0

Jens
Jens

Reputation: 72639

No. Simple as that. And why should it.

Upvotes: 1

Dima
Dima

Reputation: 23624

This is really a question of ternary operators vs regular if-statements. Neither will be faster, so it's really a matter of aesthetics/preference.

Upvotes: 1

Related Questions