Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster? Comparison or assignment?

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-written as

array[i]=true; 

This raises the question: are comparisions faster than assignments?

What about differences from language to language? (contrast between java & cpp, eg.)

NOTE: I've heard that "premature optimization is the root of all evil." I don't think that applies here :)

like image 773
jrharshath Avatar asked May 26 '09 12:05

jrharshath


2 Answers

This isn't just premature optimization, this is micro-optimization, which is an irrelevant distraction.

Assuming your array is of boolean type then your comparison is unnecessary, which is the only relevant observation.

like image 186
cletus Avatar answered Oct 12 '22 06:10

cletus


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.

like image 31
sharptooth Avatar answered Oct 12 '22 08:10

sharptooth