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.
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:
if
statement. So means an extra couple memory reads and more space unnecessarily consumed in the cache. b
is put into a register. Register reads/writes are very cheap, but they aren't free.. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With