What is faster: many ifs, or else if?

后端 未结 11 1848
夕颜
夕颜 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:11

    else if would be faster in the sense that you compare until you hit a condition that resolves to true, and you skip the rest of the ifs.

    Also consider reordering the compares in order of descending frequency.

    And using the switch statement depending on the datatype of the object you are comparing.

    However at this point, as duffymo has suggested, you would be micro optimizing. The performance gain will never be as significant if you haven't chosen the right sorting algorithm for the job first.

提交回复
热议问题