Sub topic 16
Comparing optimised and unoptimised queries
This chapter assumes you can write a lazy query with scan_parquet, filter, group_by and agg, and that you can read explain() output as covered earlier in this tutorial. Here you will use that knowledge to check what the optimiser did, confirm it did not change your results, and find out whether a slow query is slow because an optimisation was blocked.
Why compare at all
The optimiser is supposed to return the same result as the unoptimised plan, only faster. Three situations still call for a side-by-side comparison:
- You suspect a wrong result and want to rule the optimiser in or out.
- A query is slower than expected and you want to know whether a pushdown happened.
- You are benchmarking and need a fair baseline.
In all three, the method is the same. Run the query twice, once with the default optimisations and once with them disabled. Then compare the plans, the results and the timings.
A reproducible test query
The script below builds a two-million-row Parquet file in a temporary directory, so you can run it as is. The query computes a column, filters on another, groups and sorts.
import tempfile
import time
from pathlib import Path
import polars as pl
path = Path(tempfile.mkdtemp()) / "events.parquet"
n = 2_000_000
pl.select(
user_id=pl.int_range(n) % 1000,
country=(pl.int_range(n) % 5).cast(pl.String),
amount=(pl.int_range(n) % 97) * 1.5,
note=pl.lit("x" * 40),
).write_parquet(path)
lf = (
pl.scan_parquet(path)
.with_columns(total=pl.col("amount") * 2)
.filter(pl.col("country") == "3")
.group_by("user_id")
.agg(pl.col("total").sum())
.sort("user_id")
)The note column is never used by the query. That makes it a good probe for projection pushdown.
Comparing the plans
explain() takes an optimized argument. Printing both versions shows what changed.
print(lf.explain(optimized=False))
print(lf.explain())In the unoptimised plan, the scan sits at the bottom and reads every column. The filter is a separate node above the with_columns step. In the optimised plan, look for three differences:
- The scan node lists only the columns the query needs (
user_id,country,amount).noteis gone. - The
country == "3"condition appears inside the scan node as a predicate. The filter was moved belowwith_columns, which is safe because the filter does not usetotal. - The separate filter node no longer appears above the scan.
If an expected change is missing, you have found where to investigate. Common causes are covered in the barriers chapter, and a Python UDF is the usual one.
Comparing results
An optimisation that changes the answer is a bug, so check equality before you look at speed. Newer Polars versions (1.30 and later) take flags through pl.QueryOptFlags. QueryOptFlags.none() turns everything off.
optimised = lf.collect()
plain = lf.collect(optimizations=pl.QueryOptFlags.none())
print(optimised.equals(plain))This query ends in sort("user_id") and has one row per user, so the row order is fixed and equals is a valid check. Without a sort, a group_by returns groups in no guaranteed order. In that case, sort both frames on the key columns before comparing, or the comparison can fail without anything being wrong.
You can also disable one optimisation at a time. This tells you which one is responsible for a difference.
only_no_predicate = lf.collect(
optimizations=pl.QueryOptFlags(predicate_pushdown=False)
)
print(only_no_predicate.equals(optimised))Comparing timings
Time each variant several times and take the best run. A single run is dominated by file-system caching, because the first read of a file is often slower than later ones.
def best_of(fn, repeats=5):
times = []
for _ in range(repeats):
start = time.perf_counter()
fn()
times.append(time.perf_counter() - start)
return min(times)
fast = best_of(lambda: lf.collect())
slow = best_of(lambda: lf.collect(optimizations=pl.QueryOptFlags.none()))
print(f"optimised: {fast:.3f}s")
print(f"unoptimised: {slow:.3f}s")On this file the optimised run should be faster, because it reads three columns instead of four and skips non-matching rows early. The size of the gain depends on your hardware and data, so do not treat any single number as a rule.
Profiling inside a query
Total time does not say which step is expensive. LazyFrame.profile() runs the query and returns the result plus a table of per-node timings.
result, timings = lf.profile()
print(timings)The timings table has the columns node, start and end, with times in microseconds. Compare the profile of the default query with one built from a variant you suspect is blocked. For example, replace a native expression with map_elements and see which nodes grow. Profiling executes the query, so it costs as much as a normal collect.
A debugging workflow
Reading the comparison correctly
A few points prevent false conclusions:
- Equal plans are not a problem. A query on an in-memory
LazyFramewith no filter or column drop may produce identical plans. Then there is nothing to push down. - Small data hides the effect. On a few thousand rows, planning overhead and noise exceed any saving. Test on realistic sizes.
- Disabling everything is not the same as eager.
collectwith no optimisations still runs a lazy plan. It does not execute each step as a separate eager call, so it is a baseline for the optimiser, not for eager mode. - Sort before comparing. Unordered operations can return rows in different orders without either being wrong.
- Caching distorts the first run. Warm the file cache with one throwaway run before timing.
Exercises
Exercise
You run lf.collect() and lf.collect(optimizations=pl.QueryOptFlags.none()) on a query that ends in group_by("k").agg(...) with no sort. equals returns False. Does this prove the optimiser changed the result, and what should you do next?
Show answer
No. group_by does not guarantee row order, so the two frames can hold the same rows in different orders. Sort both on the key column (for example .sort("k")) and compare again. If they still differ, disable flags one at a time to find which optimisation changes the result, then build a minimal reproduction.
Exercise
The optimised explain() for your query shows a separate FILTER node above the scan, and the scan still lists all columns. Name two checks you would make and one possible cause.
Show answer
First, compare explain(optimized=False) with explain() to confirm nothing changed. Second, look at the steps between the scan and the filter for a Python UDF such as map_elements, or another opaque step. A UDF is a possible cause, because the optimiser cannot see which columns it uses or whether moving the filter past it is safe. Rewriting the step with native expressions and re-running the comparison should restore the pushdown.