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,484
  • 6
  • 56
  • 83
Rudolf Adamkovič
  • 31,030
  • 13
  • 103
  • 118

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,484
  • 6
  • 56
  • 83
1

No. Simple as that. And why should it.

Jens
  • 69,818
  • 15
  • 125
  • 179
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,161
  • 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
  • 36,249
  • 2
  • 81
  • 97