Quick Q: Is atomic decrementing more expensive than incrementing? -- StackOverflow

Quick A: No, not in general. Yes, in the specific case of a reference counted smart pointer which can take advantage of its special semantics.

Is atomic decrementing more expensive than incrementing?

In his Blog Herb Sutter writes

[...] because incrementing the smart pointer reference count can usually be optimized to be the same as an ordinary increment in an optimized shared_ptr implementation — just an ordinary increment instruction, and no fences, in the generated code.

However, the decrement must be an atomic decrement or equivalent, which generates special processor memory instructions that are more expensive in themselves, and that on top of that induce memory fence restrictions on optimizing the surrounding code.

The text is about the implementation of shared_ptr and I am not sure if his remark applies only on this or is generally the case. From his formulation I gather it is generally.

But when I think about it I can only think of "more expensive decrement" when a if(counter==0) immediately follows -- which probably is the case with shared_ptr.

Therefore I wonder if the atomic operation ++counter is (usually) always faster than --counter, or just because it is used if(--counter==0)... with shared_ptr?

Add a Comment

Comments are closed.

Comments (1)

0 0

jogojapan said on Jun 12, 2013 07:22 PM:

The link to the actual question seems to be missing. Here it is: http://stackoverflow.com/questions/16966043/is-atomic-decrementing-more-expensive-than-incrementing