Thursday, 22 May 2025

UE5: LIKELY() vs. UNLIKELY (branch-prediction)

Branch Prediction

Modern CPUs use branch prediction to guess which sequence of instructions to "pre-fetch" and execute after a conditional statement. You can provide hints to the compiler about the most likely outcome. This helps the CPU to more accurately follow the common execution path, minimizing performance-draining pipeline stalls from mispredictions. In short: it can potentially speed up your code.

Unreal Engine Usages

The best example I could find were this could be quite beneficial is pointer checks. They are very often just meant to prevent errors or crashes and can hence be written like the following:

if (LIKELY(ActorPtr)) // ActorPtr is an AActor* pointer
const FVector Location = ActorPtr->GetActorLocation();

In this example we know that it is highly likely that true will be returned for the check. This could also be used for math checks when you know a certain number will big bigger or smaller than another.

You could also use "UNLIKELY()" if a result is unlikely to be true. Just use what is easier to read or by your preference. Let's say you have the following:

TArray<double> DoubleArray;
DoubleArray.SetNumUninitialized(500);
for (int32 i = 0; i < 500; i++)
DoubleArray[i] = UKismetMathLibrary::RandomFloatInRange(0.0, 100.0);

for (const auto &Element : DoubleArray)
{
if (UNLIKELY(Element < 10.0))
{
// do something
}
}

Statistically speaking you have a 10 percent chance that the current element is smaller than 10, therefore "UNLIKELY()" can be used.

Hope this helps!

No comments:

Post a Comment