views:

252

answers:

2

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?

+6  A: 

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

Pyrolistical
You might be interested to note that the book is largely about Big-O.Why should I care? Because I don't know.
cmsjr
I agree that it is a ridiculous optimization, but knowing how each works is not worthless. +1 from me to the OP and this reply.
Ed Swangren
Pyro, thanks for insight, if not the tone.
cmsjr
You are correct, I could have said it in a nicer way, but oh well
Pyrolistical
+6  A: 

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.

David Thornley
I'm not actively performing micro-optimization, this was just some curiosity I had after seeing some partial-sort then compare algorithms.
cmsjr
OK, but the question of what operations are faster has become far more complicated since I started in this field. Modern processors are really complicated and hard to predict.
David Thornley