Sub topic 14
Common Subexpression Elimination and collect_all
This chapter assumes you can build LazyFrames, call collect() and read explain() output, as covered in earlier chapters. It covers one optimisation that works inside a single expression context, and a second that works across several queries.
The problem: the same work written twice
Expressions are often reused. A smoothed column may feed two derived columns, or two reports may start from the same filtered table. Without help, Polars would compute the repeated part once for each place it appears.
Polars removes this duplication with two related optimisations:
| Optimisation | Scope | What it shares |
|---|---|---|
| Common subexpression elimination (CSE) | One `select`, `with_columns` or `group_by().agg()` call | A repeated expression, computed once into a temporary column |
| Common subplan elimination | One query, or all queries passed to `collect_all` | A repeated part of the plan, such as a scan plus filter, cached after its first run |
Both are on by default. Neither changes results. They only avoid repeating work.
Common subexpression elimination inside one context
A subexpression is any part of an expression that can be evaluated by itself. In this query, smooth appears twice in one with_columns call:
import polars as pl
lf = pl.LazyFrame({"x": [1.0, 2.0, 3.0, 4.0, 5.0]})
smooth = pl.col("x").rolling_mean(window_size=3)
query = lf.with_columns(
a=smooth + 1,
b=smooth * 2,
)
print(query.explain())
print(query.collect())The optimiser notices that both output columns contain the same rolling_mean expression. It computes that expression once, stores the result in a temporary column, and builds a and b from the stored column. In the optimised plan, look for column names that start with __POLARS_CSER_. These are the temporary columns. The exact text of the plan differs between Polars versions, so look for the pattern rather than matching a fixed string.
The collected result has the columns x, a and b. The temporary column is dropped before the result is returned.
What counts as a shared subexpression
CSE does not cache everything it sees twice. Keep these rules in mind:
- It only compares expressions inside one context. If you write two separate
with_columnscalls, each is its own context, and the same expression in both is computed twice. - It skips trivial expressions such as a bare
pl.col("x")or a literal. Caching them would cost more than recomputing them. - It skips expressions whose result can change between evaluations, such as random sampling. Treating two such calls as one would change the result.
- The saving grows with the cost of the expression. A rolling window or a string operation benefits. A single addition does not.
CSE trades memory for time, because the temporary column stays alive until the context finishes. On very wide or very large frames, a shared expensive column adds to peak memory. This is rarely a problem, but it explains why you can switch CSE off for debugging or measuring.
Doing it by hand
CSE helps when you build expressions in Python and reuse them. You can get the same effect and make the intent obvious by naming the intermediate column in a separate step:
import polars as pl
lf = pl.LazyFrame({"x": [1.0, 2.0, 3.0, 4.0, 5.0]})
query = (
lf.with_columns(smooth=pl.col("x").rolling_mean(window_size=3))
.with_columns(
a=pl.col("smooth") + 1,
b=pl.col("smooth") * 2,
)
.drop("smooth")
)
print(query.collect())This version guarantees one evaluation whether or not the optimiser acts. Use it when you want the shared column in the output, or when a team reviewing the code should see the reuse. Rely on automatic CSE when the shared piece is a detail of the calculation.
Common subplan elimination and collect_all
CSE works on expressions. The second optimisation works on whole plans. Suppose two reports start from the same filtered data:
import polars as pl
lf = pl.LazyFrame(
{
"region": ["EU", "US", "EU", "APAC", "US"],
"product": ["a", "b", "a", "c", "a"],
"amount": [10.0, -2.0, 7.5, 3.0, 4.0],
}
)
base = lf.filter(pl.col("amount") > 0)
by_region = base.group_by("region").agg(pl.col("amount").sum())
by_product = base.group_by("product").agg(pl.col("amount").mean())
r1, r2 = pl.collect_all([by_region, by_product])
print(r1.sort("region"))
print(r2.sort("product"))If you call by_region.collect() and then by_product.collect(), Polars runs each query alone. With a CSV source, each call would scan the file and apply the filter again. pl.collect_all takes a list of LazyFrames and returns a list of DataFrames in the same order. Because it sees both plans at once, it finds that base is shared. It runs that part once, stores the result in a cache node, and lets both aggregations read from the cache.
The saving is largest when the shared part is expensive: reading a large file, a join, or a heavy filter. For in-memory data and a cheap filter, the difference is small.
Details that matter in practice
collect_allreturns a list, so unpack it in the order you passed the queries.- Sharing is detected by matching plan structure, not Python variable names. Two queries built separately but with identical scans and filters can still share work.
- The cache holds the shared result in memory until both consumers finish. For a shared part larger than memory, caching works against you. Streaming execution, covered later in this tutorial, is the better tool there.
- Common subplan elimination also applies inside a single query when the same plan appears twice, for example when a frame is joined to a filtered copy of itself.
Checking and controlling the optimisations
Use explain() to confirm that sharing happened. For CSE, look for the temporary __POLARS_CSER_ columns. For subplan elimination, look for a cache node that appears in more than one branch of the plan.
Both optimisations have flags. collect() and explain() accept comm_subexpr_elim and comm_subplan_elim, and collect_all accepts comm_subplan_elim. In recent Polars releases these flags are grouped in pl.QueryOptFlags, and the older keyword arguments are deprecated. Check the documentation for your installed version before relying on either form. Turning a flag off is useful in two cases:
- You are benchmarking and want to measure what the optimisation saves.
- You suspect an optimisation is affecting a result, and want to rule it out.
Summary of when each applies
- Repeated expression in one
with_columnsorselect: CSE handles it. Name the column yourself if you want it visible. - Repeated expression across separate
with_columnscalls: CSE does not apply. Create the named column once. - Several reports from the same filtered or joined source: pass them to
collect_all. - A shared source too large for memory: avoid caching it, and use streaming and sinks instead.
Exercise
A query uses pl.col("price").log().rolling_mean(window_size=5) in two columns of one with_columns call, and the same expression again in a later, separate with_columns call. How many times will the optimiser let Polars compute it, and how could you make it run only once?
Show answer
Twice. CSE shares the two uses inside the first with_columns call, but it does not compare expressions across separate contexts, so the later call computes it again. To run it once, compute it into a named column in one with_columns call, then refer to that column with pl.col(...) in the later steps, and drop it at the end if you do not want it in the output.
Exercise
You have three LazyFrames built from the same scan_parquet(...).filter(...) and each ends in a different group_by. You call .collect() on each in turn. What change lets Polars reuse the shared work, and what does the call return?
Show answer
Pass all three to pl.collect_all([q1, q2, q3]). Polars sees the shared scan and filter, runs it once and caches it for the three aggregations. The call returns a list of three DataFrames in the same order as the queries.