5

The common rule of thumb is to prefer using pre-increment on STL iterators in cases where the value is not immediately evaluated (i.e. you just want to increment the object/iterator). This is because in general the implementation of pre-increment is more efficient than post increment.

But what about std::atomic? If I run static analysis (using PVS studio) I get a warning saying that pre-increment should be more efficient, but when I look at the implementation of pre-increment (on Visual Studio 2015) it looks less efficient than post-increment?

Is there a general rule for using pre-increment over post-increment on STL atomic values or would it be implementation specific?

1
  • 4
    "it looks less efficient than post-increment?" How does it look less efficient? Commented Nov 29, 2016 at 10:37

2 Answers 2

4

I don't have access to windows right now, but in gcc, the difference is between

__atomic_fetch_add(&_M_i, 1, memory_order_seq_cst); 

and

__atomic_add_fetch(&_M_i, 1, memory_order_seq_cst); 

which are builtins, so you can assume the compiler knows how to optimise it.

if you don't use the result, gcc -O3 yields

 lock add DWORD PTR [rdi], 1 

for both.

If you do use the result, then gcc -O3 yields

 mov DWORD PTR [rsp-24], edi mov eax, 1 lock xadd DWORD PTR [rsp-24], eax add eax, 1 ret 

for preincrement, and omits the add eax, 1 for post increment, so technically, yes, pre-increment is less efficient by one add, but in reality that is dwarfed by the sequential memory access.

TLDR: don't worry about it

Sign up to request clarification or add additional context in comments.

Comments

1

Efficiency (at this level) is always implementation specific.

For example, as a counter to the rule of thumb "prefer pre-increment for STL iterators", it turns out that in practise few compilers will generate different code for pre-increment and post-increment. (The spurious copy of the post-increment just gets optimized away to nothing.)

2 Comments

How does the generated code for post increment differ from the pre increment if the spurious copy is optimized away? EDIT: ah, you meant that it is rare that the generated code is different. I misunderstood.
@user2079303: It doesn't. That is my point. it++; and ++it; will usually generate identical code. (Of course, if you use the result of the increment then the code will obviously be different.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.