Sub topic 14
Common subexpression elimination and collect_all
This chapter assumes you can write Polars expressions, read explain() output, and know that a LazyFrame only runs on collect(). It covers two ways Polars avoids repeating work: common subexpression elimination (CSE) inside one query, and collect_all across several queries.
The problem: the same work written twice
Analysts often reuse one expression several times in a single query. Without help, Polars would compute it each time. The expression smooth below is used twice.
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())What CSE does
Common subexpression elimination finds identical expressions in a plan. It computes each one once, stores the result in a temporary column, and lets the other expressions read that column. The results do not change. Only the amount of work does.
In the explain() output for the query above, look for temporary columns with names starting with __POLARS_CSER_. Their presence shows that the optimiser found a shared expression. The rolling mean is computed once, then a and b are built from it.
Polars applies this in two forms:
- Inside one
with_columnsorselect, shared expressions are cached in temporary columns. - Across one plan, repeated subtrees (such as the same scan and filter) can be cached and reused.
CSE helps most when the repeated expression is expensive, such as a rolling window, a sort, or a string operation. For a trivial expression like pl.col("x") + 1, the saving is negligible.
Sharing work across queries with collect_all
CSE works within one query. When you have several queries built from the same base, calling collect() on each one runs the shared part again every time. pl.collect_all takes a list of LazyFrames and runs them together, so the shared part is computed once.
import polars as pl
lf = pl.LazyFrame({
"region": ["EU", "EU", "US", "US"],
"product": ["a", "b", "a", "b"],
"amount": [10, -5, 20, 30],
})
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)
print(r2)Here base is a common prefix of both queries. With collect_all, Polars can detect it and reuse it. It returns a list of DataFrames in the same order as the input.
Checking that it worked
Use explain() to confirm CSE on a single query. If you see no __POLARS_CSER_ columns, the expressions were not identical, or the optimisation was switched off. You can compare by disabling it:
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(optimizations=pl.QueryOptFlags(comm_subexpr_elim=False)))Exercise
You run by_region.collect() and then by_product.collect() on two queries that share the same expensive filtered base. How can you avoid computing the base twice, and what does the call return?
Show answer
Call pl.collect_all([by_region, by_product]). Polars can reuse the shared base, and the call returns a list of DataFrames in the same order as the input queries.