Branchless Programming: Difference between revisions

Line 44: Line 44:


==Multiplications==
==Multiplications==
Multiplications by booleans can be used instead of switch statements.
Rather than doing
Rather than doing
<pre>
<syntaxhighlight lang="python">
if age > 10:
if age > 10:
   x = x + 10
   x = x + 10
else:
else:
   x = x - 10
   x = x - 10
</pre>
</syntaxhighlight>
you can do
you can do
<pre>
<syntaxhighlight>
y = 2 * (age > 10) - 1
y = 2 * (age > 10) - 1
x = x + 10 * y
x = x + 10 * y
Line 58: Line 60:
y = age > 10
y = age > 10
x = x + 10 * y - 10 * (1-y)
x = x + 10 * y - 10 * (1-y)
</pre>
</syntaxhighlight>


These are micro optimizations but they are sometimes useful for speeding up GPU shaders.
These are micro optimizations but they are sometimes useful for speeding up GPU shaders.