Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's more expensive, comparison or assignment?

I've started reading Algorithms and I keep wondering, when dealing with primitives of the same type, which is the more expensive operation, assignment or comparison? Does this vary a great deal between languages?

like image 888
cmsjr Avatar asked Mar 09 '09 19:03

cmsjr


2 Answers

What do you think?

At the lowest level one does two reads, the other does a read and a write.

But why should you really care? You shouldn't care about performance at this level. Optimize for Big-O

like image 99
Pyrolistical Avatar answered Nov 25 '22 13:11

Pyrolistical


Micro-optimization is almost always the wrong thing to do. Don't even start on it unless the program runs too slowly, and you use a profiler to determine exactly where the slow parts are.

Once you've done that, my advice is to see about improving code and data locality, because cache misses are almost certainly worse than suboptimal instructions.

That being done, in the rather odd case that you can use either an assignment-based or comparison-based approach, try both and time them. Micro-optimization is a numbers game. If the numbers aren't good enough, find out why, then verify that what you're doing actually works.

So, what do you mean by a comparison? Conditional jumps cause problems to any vaguely modern processor, but different processors do different things, and there's no guarantee that any given one will slow things down. Also, if either causes a cache miss, that's probably the slower one no matter what.

Finally, languages are normally compiled to machine code, and simple things like comparisons and assignments will normally be compiled the same. The big difference will be the type of CPU.

like image 30
David Thornley Avatar answered Nov 25 '22 11:11

David Thornley