What is faster: many ifs, or else if?

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

    If the values are integers you may achieve an optimisation by using a table lookup. E.g. say you have 256 values that map into 7 days somehow, you could set up an array with 256 cells and each cell contained the day of week you wanted. Then instead of:

    
    if ( value == 0 ) {
      dayofweek = 1;
    } else if ( value == 1 ) {
      dayofweek = 2;
    } else if ( value == 2 ) {
      dayofweek = 3;
    } else if ...
    

    .. you could have..

    
    dayofweek = lookuparray[value];
    

    Of course, if you use this technique, then you should check the bounds of value first.

提交回复
热议问题