bcquality/community/knowledge/performance/order-case-branches-by-frequency.md
Jesper Schulz-Wedde 0540c7bf6e Reframe seed-article banners as community contribution invitations
The 35 articles still in their seed form previously carried a banner
reading "Seed article. ... Domain stewards should expand, restructure,
and refine as needed." For a community preview, that phrasing reads as
"TODO left in production" to first-time visitors.

Replace all three banner variants (performance-seeded, security-seeded,
community-ported) with a single positive invitation:

> Contributions welcome — open a PR to refine or extend this article.

Content and structure of the articles are unchanged; only the leading
quote block differs. Articles that had their banner fully stripped in
the earlier triage pass (the showcase-grade ten) are unaffected.
2026-04-23 17:31:36 +02:00

1.5 KiB

bc-version domain keywords technologies countries application-area
all
performance
case
branch
frequency
control-flow
hot-path
al
w1
all

Order case branches by frequency

Contributions welcome — open a PR to refine or extend this article.

Description

The AL case statement evaluates branches in the order they appear. When the distribution of the discriminator is heavily skewed — one or two values handle the vast majority of records, and the rest handle edge cases — the average cost of the statement is dominated by how many branches precede the common one. For evenly distributed discriminators the order does not matter; for skewed distributions it changes the hot-path cost of every call site.

Best Practice

Where the runtime frequency of values is known or measurable, list the common branches first. An else arm that handles unexpected values belongs last. When the common branch is also the simplest to evaluate, the placement compounds: the hot path is both short and cheap, and the uncommon branches are never touched on typical records.

See sample: order-case-branches-by-frequency.good.al.

Anti Pattern

Ordering branches alphabetically, by enum declaration order, or by "logical grouping" when the runtime distribution is heavily skewed. Every common record pays the cost of evaluating every uncommon branch first; on a posting routine processing thousands of rows the overhead is measurable.

See sample: order-case-branches-by-frequency.bad.al.