in reply to Weird performance issue with Strawberries and Inline::C
I had a longer answer, but ran it past Claude.AI and it knew a lot more about the topic than I did and my answer would have been wrong. Of course this could be inaccurate/wrong too, but it looks more accurate than what I was going to say. At the risk of offending people, here's is a portion of its answer:
On x86-64, there isn't a direct conditional arithmetic instruction like you describe, but there are several approaches that can eliminate branches:
- CMOVcc (Conditional Move) - The most common approach
or more directly:; Assuming condition result is in a flag mov eax, i lea edx, [rax + 1] ; edx = i + 1 cmovnz eax, edx ; if condition != 0, eax = edx mov i, eaxlea edx, [i + 1] test condition, condition cmovnz i, edx ; conditionally move the incremented value- SETcc (Set Byte on Condition) - Convert condition to 0/1
This is often the most efficient for your exact use case - it turns the condition into a 0 or 1, then unconditionally adds it.xor eax, eax test condition, condition setnz al ; al = (condition != 0) ? 1 : 0 add i, eax ; i += 0 or 1- ADC/SBB (Add/Subtract with Carry) - If condition is in carry flag
; If your condition sets the carry flag: adc i, 0 ; i += carry flagThe SETcc + ADD pattern is typically what compilers generate for branchless if (cond) i++, and it's usually faster than a branch for unpredictable conditions.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Weird performance issue with Strawberries and Inline::C
by tonyc (Hermit) on Oct 12, 2025 at 21:14 UTC | |
by syphilis (Archbishop) on Oct 13, 2025 at 02:53 UTC | |
by NERDVANA (Priest) on Oct 13, 2025 at 02:51 UTC | |
|
Re^2: Weird performance issue with Strawberries and Inline::C
by ikegami (Patriarch) on Oct 13, 2025 at 00:35 UTC | |
by NERDVANA (Priest) on Oct 13, 2025 at 02:46 UTC |