Which is faster? Comparison or assignment?

前端 未结 12 1204
抹茶落季
抹茶落季 2020-12-05 04:16

I\'m doing a bit of coding, where I have to write this sort of code:

if( array[i]==false )
    array[i]=true;

I wonder if it should be re-w

12条回答
  •  遥遥无期
    2020-12-05 04:38

    If you just want to flip the values, then do:

    array[i] = !array[i];
    

    Performance using this is actually worse though, as instead of only having to do a single check for a true false value then setting, it checks twice.

    If you declare a 1000000 element array of true,false, true,false pattern comparision is slower. (var b = !b) essentially does a check twice instead of once

提交回复
热议问题