Sub topic 15
Replacing Python UDFs with built-in functions
This chapter assumes you know basic PySpark DataFrames, can read a query plan (see the earlier chapter on EXPLAIN), and know that Photon is Databricks' native vectorized engine.
Why UDFs slow queries down
A Python user-defined function (UDF) is a function you write in Python and call from a query. Spark cannot look inside it. The optimizer treats it as a black box, so it cannot reorder, push down, or simplify the logic.
A UDF has three costs:
- Serialization. Rows are copied from the JVM to a Python worker process and back.
- Row-by-row execution. The standard Python UDF runs your function once per row, not on batches of values.
- No Photon. Photon runs only operators it supports natively. A Python UDF forces that part of the plan to run in the standard Spark path.
Built-in functions avoid all three. They run inside the engine, the optimizer understands them, and Photon can execute most of them on columnar batches.
The same logic, two ways
from pyspark.sql import functions as F
from pyspark.sql.types import StringType
# Slower: a Python UDF runs row by row outside the native engine.
normalize_udf = F.udf(lambda s: s.strip().upper() if s is not None else None, StringType())
slow = df.withColumn("region_norm", normalize_udf("region"))
# Preferred: built-in functions stay inside the optimized engine.
fast = df.withColumn("region_norm", F.upper(F.trim("region")))Both versions return the same values, including null for null input. The second one is shorter and needs no null check, because built-in functions already propagate nulls.
Confirm the difference in the plan
Call explain() on both DataFrames and compare.
slow.explain()
fast.explain()The slow plan contains a BatchEvalPython (or similar Python evaluation) node. The fast plan has only ordinary projection expressions. In the Query Profile, the fast version can show Photon operators for that step, while the UDF version shows a non-Photon operator at the UDF.
How to replace a UDF
- Search the [function reference](https://spark.apache.org/docs/latest/api/sql/index.html) for a built-in that does the job. String, date, math, array, map, and JSON functions cover many cases.
- Express conditionals with
F.when(...).otherwise(...)instead ofifstatements in Python. - Combine several built-ins, as with
upper(trim(...))above. - For custom logic that is still needed, try
F.exprwith a SQL expression, or higher-order functions such astransformandfilterfor arrays.
Common mistakes
- Wrapping a built-in in a UDF out of habit, for example writing
udf(lambda x: x.lower())instead ofF.lower. - Forgetting null handling in a UDF. A
Noneinput raises an error inside the Python worker and fails the task. - Assuming a faster plan without checking. Always compare the plan or Query Profile, and time both versions as described in the benchmarking chapter.
Exercise
A query uses udf(lambda d: d[:7]) to take the first seven characters of a string column order_month. Name a built-in replacement, and explain why it helps Photon.
Show answer
Use F.substring("order_month", 1, 7) (or F.col("order_month").substr(1, 7)). It is a native expression, so the optimizer can see it and Photon can run it on columnar batches. The UDF forces that step to run row by row in a Python worker outside Photon.