What is faster: many ifs, or else if?

后端 未结 11 1843
夕颜
夕颜 2020-12-29 22:35

I\'m iterating through an array and sorting it by values into days of the week.

In order to do it I\'m using many if statements. Does it make any differ

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-29 23:12

    I doubt that a micro optimization like this will make a measurable difference in your code.

    Your sorting algorithm is more likely to be the source of a performance problem. Which sorting algorithm you choose will be critical, not many "ifs" versus "else if".

    UPDATE:

    The points made by others about "else if" being a better choice, due to its early exit and exclusive logic characteristics, suggest that it should be preferred over "if" in this case.

    But the point about algorithm choice still stands - unless your data set is very small.

    It's obvious that O(log n) would be better than O(n^2), but size of dataset matters as well. If you have only a few elements, you might not notice the difference. In that case, coding an inefficient method in the cleanest, most readable, most easily understandable at a glance could be your best bet.

提交回复
热议问题