Member-only story
Understanding C++20: Optimization Hints with likely and unlikely Attributes
Optimizing Code Performance with Proper Use of likely and unlikely
C++20 introduced the [[likely]]
and [[unlikely]]
attributes, which provide optimization hints to the compiler, indicating that the corresponding code paths are likely or unlikely to be executed.
At first glance, these attributes seem useful for optimization and potentially improving performance. However, this is not necessarily the case.
The C++ standard draft explicitly states: Excessive usage of either of these attributes is liable to result in performance degradation.
In other words, overusing either attribute may lead to a performance decline.

So, when are these attributes useful, and when are they unnecessary?
Here are some personal views on this topic.
1. Principles
When using these attributes, follow these guidelines:
- Use with caution: Only apply these attributes when you are certain that a branch or path is highly likely or unlikely to occur at runtime.