Is it faster to avoid writes when the values might be the same

82 views Asked by At

On SMP machines is there a performance benefit to #2 vs #1:

1) x = 0;

or

2) if (x) x = 0;

I was thinking that the behind the scenes overhead to manage cache coherency between the CPUs might have some cost. Am I nuts?

2

There are 2 answers

0
R.. GitHub STOP HELPING ICE On BEST ANSWER

Even with single-threaded code, the latter can have an advantage if the object lies in copy-on-write memory (for example, a private mapping of a file, or almost any writable memory after a fork). I suspect the advantage you're asking about is real too, at least on systems like x86 where memory consistency is handled automatically. On such machines, writing to memory that might be in another cpu's cache will invalidate the cached copy (actually the entire cache line). Just reading won't do any harm. Of course, if this is memory that's potentially being modified and shared by multiple threads, it needs to be protected by synchronization mechanisms anyway, and then you probably lose most or all of the advantage.

0
Francis Upton IV On

It has to manage the cache coherency even if you are reading, so I don't think it's going to buy you anything. And it also is going to largely depend on what the compiler does. If you really care, I would benchmark it on the system you are using.