Why is a Python user-defined function udf so much slower than Spark's built-in functions?
A Python UDF runs in Python workers beside the executor JVM: rows are serialised there and back, and Catalyst sees a black box — no codegen, no filter on its output reaching the scan. Rewrite it with built-ins; if Python is a must, a pandas UDF works on Arrow batches.
- Blaming Python arithmetic speed instead of the per-row serialisation
- Expecting a filter on the UDF's result to be pushed down to the scan
- Reaching for a pandas UDF before checking whether built-ins express the logic
- What does Arrow change for a pandas UDF compared with a plain Python UDF?
- How would you spot a Python UDF's cost in the physical plan?
A plain Python UDF calls the function once per row in a Python process. Up to Spark 4.1 it shows up in the physical plan as BatchEvalPython and the rows travel pickled; since 4.2 regular Python UDFs are Arrow-optimised by default (spark.sql.execution.pythonUDF.arrow.enabled), so the plan shows ArrowEvalPython and the transfer is batched, but the per-row call and the serialisation remain. To Catalyst it is an opaque call either way, so whole-stage codegen breaks at it and a predicate on its result cannot be pushed into the Parquet read.
from pyspark.sql import functions as F
from pyspark.sql.types import StringType
# slow: every row goes to Python and back
@F.udf(returnType=StringType())
def clean_phone(s):
return None if s is None else "".join(ch for ch in s if ch.isdigit())
df.withColumn("phone", clean_phone("raw_phone"))
# fast: the same with a built-in function, stays in the JVM
df.withColumn("phone", F.regexp_replace("raw_phone", r"\D", ""))When the logic cannot be expressed with built-ins, a pandas UDF (@F.pandas_udf, also ArrowEvalPython in the plan) receives whole columns as pandas Series from Arrow batches and computes them vectorised: the per-row overhead drops sharply, though the optimiser still cannot see inside it.