Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read then conditional write vs. write

Which is, on average, faster - check the value then, if needed, assign, or simply assign? Or, in C++ terms:

bool b;
if(b)
    b = false;

or

b = false;

Assume that the if() condition is true with 50% probability. The answer will be, most likely, highly architecture dependent - please voice your low-level considerations. Writing always dirties the cache line - right? So by avoiding a write we avoid a cache flush in 0.5 cases. But a smart enough cache might detect a trivial write and not dirty itself. But the unconditional write is always exactly one memory operation, and read-write is, on average, 1.5 operations.

Disclaimer: this is a curiosity question, not a problem I actually face.

like image 830
Seva Alekseyev Avatar asked Mar 03 '10 22:03

Seva Alekseyev


1 Answers

Branches are expensive on modern CPUs and memory access is expensive on embedded/older CPUs. So the flat just-assign will always be faster unless you have some kinda weird memory that takes longer to write than read(hint: you don't)

It is worse for these reasons specifically:

  • A branching instruction. This may be predicted away by the processor, but it still incurs an overhead possibility.
  • 2 memory accesses instead of 1. Reading and Writing on most forms of memory are the same speed, so why do it twice when you can do it once?
  • More code overhead. this is a micro one, but more instructions must be emitted to do the if statement. So means an extra couple memory reads and more space unnecessarily consumed in the cache.
  • And for the pessimistic, it could mean that the C++ compiler decides to put this variable into a register instead of other more necessary variables..
  • Also, if you assume that b is put into a register. Register reads/writes are very cheap, but they aren't free..
like image 144
Earlz Avatar answered Sep 20 '22 17:09

Earlz