mambo_sun
mambo_sun

Reputation: 539

Always assign vs check equality and assign

Is there any noticeable performance difference between:

if (a != b) a = b; and a = b;

when a and b are both of the same built-in type like int or bool or maybe a really simple and small struct?

As I understand second expression will write to memory every time (which I assume is a heavier operation than read), while first one will do it only if a and b are not already equal.

Or probably it depends on how often is b value changed?

I understand that it's more of "++i vs i++" kind of a question, I am curious though

Upvotes: 1

Views: 263

Answers (1)

No-Bugs Hare
No-Bugs Hare

Reputation: 1638

It really depends.

For x86 CPUs, cost of operations involved in your program, will be roughly as follows:

  • non-cached read (i.e. read from RAM which is not cached yet): ~100 clocks
  • cached read: 3 to ~10 clocks
  • register read: 1/2 clock (value is very rough, as there is no such single operation "read")
  • write: varies and depends, but often ~1 clock
  • comparison: up to 5-10 clocks if compiler guess "which branch will happen" is wrong (this is known as "pipeline stall"); otherwise - 1 clock.

Using this information, you might be able to make some guesstimates ;-).

For other (non-x86) desktop/server/mobile CPUs numbers will be different, but overall picture will be more or less the same.

Upvotes: 1

Related Questions