Member-only story

Understanding C++20: Optimization Hints with likely and unlikely Attributes

Optimizing Code Performance with Proper Use of likely and unlikely

Fracis
Level Up Coding
2 min readSep 27, 2024

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.

https://eel.is/c++draft/dcl.attr.likelihood#note-2

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:

  1. 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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Written by Fracis

Stories About C Plus Plus,Arrow and DuckDB contributor

Responses (1)

Write a response