2

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;
Dima
  • 23,268
  • 5
  • 53
  • 82
Rudolf Adamkovič
  • 30,008
  • 11
  • 100
  • 116

4 Answers4

1

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.

Dima
  • 23,268
  • 5
  • 53
  • 82
1

No. Simple as that. And why should it.

Jens
  • 65,924
  • 14
  • 115
  • 171
1

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.

Vishal
  • 2,043
  • 14
  • 25
0

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.

janneb
  • 34,114
  • 2
  • 76
  • 93