Which is faster? Comparison or assignment?

前端 未结 12 1205
抹茶落季
抹茶落季 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:46

    Well, since you say you're sure that this matters you should just write a test program and measure to find the difference.

    Comparison can be faster if this code is executed on multiple variables allocated at scattered addresses in memory. With comparison you will only read data from memory to the processor cache, and if you don't change the variable value when the cache decides to to flush the line it will see that the line was not changed and there's no need to write it back to the memory. This can speed up execution.

提交回复
热议问题