Skip to content

Instantly share code, notes, and snippets.

@GrabYourPitchforks
Created January 31, 2018 08:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GrabYourPitchforks/b3cd59ce9dffd864e9dcb5b5f4dc5208 to your computer and use it in GitHub Desktop.
Save GrabYourPitchforks/b3cd59ce9dffd864e9dcb5b5f4dc5208 to your computer and use it in GitHub Desktop.
// 'valueIfTrue' and 'valueIfFalse' really should be compile-time constants for maximum throughput.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int ConditionalSelect(bool condition, int valueIfTrue, int valueIfFalse)
{
// From https://software.intel.com/sites/default/files/managed/9e/bc/64-ia-32-architectures-optimization-manual.pdf
// Example 3.2. We're taking advantage of the fact that bools are passed by value as 32-bit integers,
// so we'll blit it directly into a 1 or a 0 without a jump.
// Codegen will emit a movzx, but on Ivy Bridge (and later) the CPU itself elides the instruction.
return ((-Unsafe.As<bool, int>(ref condition)) & (valueIfTrue - valueIfFalse)) + valueIfFalse;
}
@GrabYourPitchforks
Copy link
Author

It should go without saying - please don't use this in production. :)

@blowdart
Copy link

blowdart commented Feb 1, 2018

You're a horrible person. But you already knew that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment