Conversation
|
It is reasonable. |
|
Merged. |
| } | ||
| bool isNegative = e < 0; | ||
| e = isNegative ? -e : e; | ||
| *buf++ = isNegative ? '-' : '+'; |
There was a problem hiding this comment.
Replacing if statements with ternary operators doesn't make the code branchless. It's just different syntax.
There was a problem hiding this comment.
Correct, although the new code is more elegant I believe. No?
The PR removed a branch later on by always printing two digits (a common convention). So this removes a branch in some cases and might be faster.
There was a problem hiding this comment.
The branchless here means no jmp or other branch instruction in assembly code, using comv instead.
So the ternary operators is just a easy way for compiler to generate comv, the clang generated assembly code is
mov ecx, esi
neg ecx
cmovs ecx, esi
shr esi, 31
add sil, sil
add sil, 43
mov byte ptr [rdi], sil
But I have to say, even with or without ternary operator, the compiler still generate the same assembly code, see here
There was a problem hiding this comment.
@taoliq Yes. But the reason for it is due to how the code is written. In both branches in the old code, we do much the same work... so that the compiler can recognize the pattern and optimize accordingly.
According #1450 , refactor some code to avoid branches