As a rookie programmer, I've only recently been digging into benchmarking, and have been comparing various ways of accomplishing the same task in terms of speed.
Most of the time, the result is either that the difference in speed is negligible or that it is so huge that I'm definitely going to use the faster option.
That leaves the cases in the middle. If I understand correctly from reading similar questions and answers, the consensus of software engineers is that any optimizations that clobber the readability of your code or make you expend valuable time should be left until you've run into a performance issue and identified what code is the bottleneck. That seems entirely reasonable to me.
However, what is "readable" and what is not? I have a very concrete example in mind. Take a look at this benchmark in JavaScript: https://jsperf.com/cond-vs-mult. It compares the use of implicit conditioning through multiplication with a boolean value with an explicit conditional by using the ternary operator ?
. Now, it costs me no time or effort to simply write the faster version in all cases, so the only concern in my mind is readability.
My opinion after reading comments & answers
I don't agree with the duplication vote. I understand how this is remarkably similar to the linked question, but this was mainly about the readability of an implied conditional. Can you answer the linked question with an answer such as "the ternary operator is much easier to read than addition by a product with a boolean value"? No, but you can this one.
There could - but has not yet been - an underlying answer to both questions. This would have to invoke the idea of signaling, as done by keywords such as if
or nearly universal functions such as strlen
. Straying away from any such universal methods of doing something towards a language-specific or even implementation-specific method is bound to be less readable, thus constituting a micro-optimization, on which the consensus is clear. However, as it stands, the answers have only concluded the ternary operator is more readable and have thus have been unique to this question. The underlying discussion about micro-optimization, as I tried to make clear by mentioning this in my question, was not the main topic of the question. I will adjust the wording of the question to highlight this. So I really don't consider my question a duplication to the linked one.