Sub topic 14
When iterators are slow and what to do about it
This chapter assumes you can write SUMX, AVERAGEX, and RANKX measures, and that you understand row context, filter context, and context transition. It covers when iterators cost more than a plain column aggregation and how to reduce that cost. It does not cover query-plan tools in detail.
Where the cost comes from
DAX runs on two engines. The storage engine scans compressed columns and is very fast at simple work such as sums, counts, and grouping. The formula engine handles everything else, including logic and arithmetic it cannot push down, and it works with materialized results.
An iterator creates cost in three ways:
- It visits each row of its table argument, so cost grows with the number of rows.
- It evaluates its expression once per row. If the expression is complex, that work repeats for every row.
- If the expression contains a measure reference, context transition runs for each row. Each transition builds a filter context from the current row and evaluates the measure inside it.
A plain SUM ( Sales[Amount] ) is handled by the storage engine as one scan of one column. SUMX ( Sales, Sales[Amount] ) returns the same number, and the engine usually rewrites it to the same plan. The cost appears when the expression is more than a column reference.
Cheap iterators and expensive iterators
Not every iterator is slow. The engine can often push a simple per-row expression into a single storage engine query. The expression from the SUMX chapter is an example.
Sales Amount =
SUMX (
Sales,
Sales[Quantity] * Sales[Net Price]
)The multiplication involves columns of one table, so the storage engine can compute it in one pass over Sales. This is fast, even on large tables.
Now compare it with an iterator that calls a measure per row.
Avg Sales per Customer =
AVERAGEX (
VALUES ( Customer[CustomerKey] ),
[Sales Amount]
)Here the iteration runs over customers. For each customer, context transition filters Sales to that customer and evaluates [Sales Amount]. With a million customers, this means a very large number of evaluations. The engine can often batch these into a few storage queries, but the formula engine still handles the per-customer results.
The table below gives a rough guide. Actual behavior depends on the model and engine version, so always measure.
| Pattern | Typical cost | Reason |
|---|---|---|
| `SUM ( Sales[Amount] )` | Lowest | One column scan in the storage engine |
| `SUMX ( Sales, Sales[Quantity] * Sales[Net Price] )` | Low | Arithmetic over one table is usually pushed to the storage engine |
| `SUMX ( Sales, Sales[Quantity] * RELATED ( Product[Unit Cost] ) )` | Low to moderate | RELATED follows a relationship, which the engine can usually still handle in one query |
| `AVERAGEX ( VALUES ( Customer[CustomerKey] ), [Sales Amount] )` | Moderate to high | Context transition for each customer |
| `RANKX ( ALL ( Product[Product Name] ), [Sales Amount] )` | High on large item sets | The ranking table is evaluated for every cell that shows a rank |
RANKX multiplies the work
RANKX is the iterator most likely to cause trouble. Consider the measure from the earlier chapter.
Product Rank =
RANKX (
ALL ( Product[Product Name] ),
[Sales Amount],
,
DESC,
Dense
)For each cell in a visual that shows a rank, RANKX evaluates [Sales Amount] for every product in the ranking table. If the visual shows 50 products and the model has 10,000 products, that is 50 × 10,000 evaluations of the measure. DAX can cache some of this, but the cost grows with the product of the two sizes.
Three habits reduce this:
- Rank a smaller set. Rank a category or a filtered list instead of every product, when the business question allows it.
- Keep the ranked expression simple. A cheap base measure inside RANKX costs far less than a measure built from nested CALCULATE calls and time intelligence.
- Return blank where a rank has no meaning. Total rows evaluate the ranking over the full table, and the guard avoids that work.
Product Rank Selected =
IF (
HASONEVALUE ( Product[Product Name] ),
RANKX (
ALLSELECTED ( Product[Product Name] ),
[Sales Amount],
,
DESC,
Skip
)
)The IF also protects correctness, as the previous chapter explained. Here it avoids a full ranking computation for the total row.
Common causes of slow iterators
Iterating over a wide fact table when a narrow table would do
Iterating over Sales with ten million rows to compute something that depends only on the product visits ten million rows. If the result depends on the product alone, iterate over VALUES ( Product[Product Name] ), which may have a few thousand rows. Be careful, though. Changing the iterated table changes the meaning of the result. Averaging per product is not the same as averaging per sales row.
Calling a measure that is itself expensive
A measure reference inside an iterator is evaluated once per row. If that measure uses CALCULATE with FILTER over a large table, the cost is multiplied by the number of rows. Move work out of the iterator where you can. Compute helper values once with a variable before the iteration, when they do not depend on the current row.
Sales vs Average Product =
VAR AvgProductSales =
AVERAGEX (
VALUES ( Product[Product Name] ),
[Sales Amount]
)
VAR ThisSales = [Sales Amount]
RETURN
ThisSales - AvgProductSalesVariables are evaluated once, where they are defined. Writing AVERAGEX twice in the same expression would run it twice.
Using FILTER over a whole table as the table argument
FILTER ( Sales, Sales[Quantity] > 1 ) forces row-by-row evaluation of a condition across the full table. A column-based filter argument in CALCULATE is often cheaper, because the engine can resolve it as a simple filter on one column.
Multi Unit Sales =
CALCULATE (
[Sales Amount],
Sales[Quantity] > 1
)This gives the same answer as SUMX ( FILTER ( Sales, Sales[Quantity] > 1 ), Sales[Quantity] * Sales[Net Price] ) in most models. It lets the storage engine apply the condition during the scan. Test both forms on your own data, because the difference depends on the model.
Nested iterators
An iterator inside an iterator multiplies the row counts. A SUMX over customers that calls a measure containing a SUMX over Sales is a normal and often necessary pattern. A SUMX over Sales that contains an AVERAGEX over Sales is a quadratic pattern. It can be very slow, so look at it first when a measure is slow.
What to do about it
Follow this order. Stop when the measure is fast enough.
- Measure first. Use Performance Analyzer in Power BI Desktop to find the slow visual and copy its query. Run the query in DAX Studio with Server Timings turned on.
- Read the timings. A high share of formula engine time, or a very large number of storage engine queries, points to a per-row cost. A small number of storage queries with high storage time points to a large scan.
- Replace the iterator with a column aggregation if one gives the same result.
SUMX ( Sales, Sales[Amount] )becomesSUM ( Sales[Amount] ). - Reduce the rows iterated. Use
VALUESof a column instead of a whole fact table when the grain allows it. - Simplify the per-row expression. Remove measure references that are not needed, and use variables for values that do not change per row.
- Consider a calculated column. If a per-row value never depends on filter context, such as
Quantity * Net Price, a calculated column stores it once at refresh time. This trades model size and refresh time for query speed. Use it only when the measure is still too slow after the earlier steps.
Edge cases and cautions
- Do not rewrite for speed without checking the result. Replacing
AVERAGEXover customers with a simpleDIVIDEof totals changes the meaning when some customers have blank sales. The first counts only customers with a non-blank result, and the second may not. - Small models rarely need any of this. If a measure responds in a few milliseconds, readability matters more than saving a scan.
- Speed depends on cardinality, the number of distinct values in a column. A SUMX over 100,000 rows is rarely a problem. The same pattern over 100 million rows may be.
- Engine behavior changes between versions. A rewrite that helped last year may do nothing now, so re-test after upgrades.
Exercise
A report page shows a table of 200 products with the measure Product Rank, defined as RANKX over ALL ( Product[Product Name] ) using [Sales Amount]. The model has 20,000 products and the page is slow. Name two changes that could reduce the work, and say one risk of each.
Show answer
First, rank a smaller set, for example ALL of Product[Product Name] restricted to one category with a filter, or ALLSELECTED when slicers already narrow the list. The risk is that the ranks change meaning, because each product is now ranked against fewer competitors. Second, simplify the ranked measure or return blank in total rows with HASONEVALUE. The risk with simplifying is that a changed base measure may no longer match other numbers in the report, so verify results after the change. Measuring in DAX Studio first shows which change helps.
Exercise
You have SUMX ( Sales, Sales[Quantity] * Sales[Net Price] ) and it is fast. Your colleague proposes replacing it with a calculated column Sales[Line Amount] and SUM ( Sales[Line Amount] ). What do you gain, what do you pay, and when is it worth doing?
Show answer
You gain a plain column aggregation that needs no per-row arithmetic at query time. You pay with extra model size, because the column is stored, and with longer refresh time, because it is computed during refresh. It is worth doing only when the iterator is measurably slow after simpler fixes, since the original SUMX is often already pushed to the storage engine and runs about as fast.