Short-Circuiting Architecture & CPU Branch Misprediction Traps
1Concept
Logical `&&` and `||` evaluate left-to-right and halt immediately when the result is determined. Placing high-probability fast checks on the left prevents CPU branch mispredictions and skips costly database or I/O operations.
2Architecture Diagram
if (FastLocalCheck() && ExpensiveDatabaseCheck())
│
Is False?
├── YES ──> Skip ExpensiveDatabaseCheck() (Huge latency savings)
└── NO ──> Proceed to ExpensiveDatabaseCheck()3Code Example
C# 13 & .NET 9
using System;
public class ShortCircuitDemo
{
public static bool FastInMemoryCheck(int id) => id > 0;
public static bool ExpensiveDatabaseCheck(int id)
{
Console.WriteLine("Executing expensive DB check...");
return true;
}
public static void Main()
{
int invalidId = -5;
// FastInMemoryCheck evaluates to false -> DB check is skipped!
if (FastInMemoryCheck(invalidId) && ExpensiveDatabaseCheck(invalidId))
{
Console.WriteLine("Authorized.");
}
else
{
Console.WriteLine("Access Denied (Short-circuited without DB call).");
}
}
}4Expected Output
Access Denied (Short-circuited without DB call).
5Key Takeaways
- ✓Order boolean operands from cheapest to most expensive.
- ✓Never place side-effect mutating functions inside short-circuit conditions.
- ✓Modern CPU branch predictors achieve >98% accuracy on predictable loops.