0

Add some guidance on [[likely]]/[[unlikely]].

This was requested in http://crbug.com/40256217#comment46.

Bug: 40256217
Change-Id: Ib087d2aa6b24fad2103c7474d2f1a02750148fe9
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/6363475
Reviewed-by: Egor Pasko <pasko@chromium.org>
Commit-Queue: Egor Pasko <pasko@chromium.org>
Auto-Submit: Peter Kasting <pkasting@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1434089}
This commit is contained in:
Peter Kasting
2025-03-18 06:19:05 -07:00
committed by Chromium LUCI CQ
parent 4c9da1ea9a
commit b053a83b10

@ -433,4 +433,20 @@ cases:
function, and only if the code does not refer to symbols whose declarations
are `#ifdef`ed away. Don't unconditionally declare debug-only symbols just
to use this technique -- only use it when it doesn't require additional
tweaks to the surrounding code.
tweaks to the surrounding code.
## Use [[likely]] and [[unlikely]] sparingly
C++20 adds the `[[likely]]` and `[[unlikely]]` attributes, which inform the
compiler whether code is likely to be executed or not. Use these sparingly.
* Intuition is often inaccurate, and branch predictors are very good. It's easy
to accidentally pessimize performance with these, so they should only be used
when the likelihood is well-known and the performance benefit is justified.
* Future code changes can make these annotations inaccurate even if they were
accurate when first added. This is hard to notice.
* PGO data overrides these annotations, so if they're reached during profiling,
official builds won't benefit from them anyway. Thus the primary benefit is
for non-PGO-optimized builds, e.g. making execution on bots faster or having
local developer builds behave more like an official build.
* The added verbosity can marginally decrease readability.