bcquality/microsoft/knowledge/performance/avoid-calcfields-in-loops.md
Jesper Schulz-Wedde 9a4198eb28 Add [all] sentinel to bc-version; apply to version-agnostic knowledge
Most of the corpus — FindSet/SetLoadFields/CalcFields patterns, permission
sets, SingleInstance codeunits, DataClassification, IsolatedStorage,
transaction scope, SecretText — describes BC platform behaviour that is
identical across supported versions. The seed [26..28] range on every
file implied a version-specificity the content does not actually have,
and there was no way to express "applies to every version" in the
schema the way [w1] and [all] already do for countries and
application-area.

Extend the v1 schema with a universal sentinel for bc-version, parallel
to the sentinels already defined for the other dimensions:

  bc-version: [all]         # applies to every BC version

[all] is mutually exclusive with explicit versions. Range shorthand
([26..28]) and explicit lists ([26, 27, 28]) continue to work for files
genuinely tied to a version-gated API or deprecation.

Update read.md (field definition, matching semantics, partial-context
rule), write.md (default to [all], use ranges only with a concrete
reason), README.md (frontmatter example), and the CI validator. All
forty existing knowledge files and the three action skills convert to
[all]; none of the current content is version-gated. Validator passes.
2026-04-23 16:00:03 +02:00

27 lines
1.1 KiB
Markdown

---
bc-version: [all]
domain: performance
keywords: [calcfields, flowfield, loop, n-plus-one]
technologies: [al]
countries: [w1]
application-area: [all]
---
# Do not call CalcFields inside loops
## Description
CalcFields evaluates one or more FlowFields for the current record by issuing a separate SQL aggregation. Called inside a loop over a record set, it becomes an N+1 problem: one aggregate per row. For any non-trivial set on a ledger-entry-backed FlowField this is orders of magnitude slower than the equivalent batched query.
## Best Practice
Move CalcFields out of the iteration. If the total is what you need, use CalcSums on the filtered parent set. If row-by-row FlowField values are needed, reshape the computation so the aggregate runs once — for example by joining against a temporary table populated in a single batched query.
See sample: `avoid-calcfields-in-loops.good.al`.
## Anti Pattern
Calling CalcFields inside `repeat ... until Next() = 0` on a hot parent record is the textbook N+1 pattern. Even a modest parent set size (hundreds of rows) turns into thousands of round-trips.
See sample: `avoid-calcfields-in-loops.bad.al`.