Skip to content
Bronze 8 min read 2 practice problems ↓

Why DataFrames are faster than RDDs

The same aggregation can be written with RDDs or with DataFrames, and the DataFrame version is often many times faster. This lesson shows the five reasons why, from reading less data to code generation, and why they all disappear the moment a step becomes a Python lambda.

Step 2 · Spark internals · Bronze · How a job runs, lesson 3 of 5

Read first: RDDs, DataFrames and Datasets (skip if you know it)

In plain words first

A moving company given a labelled inventory can plan: take only the chairs, pack them tightly, send one van. Given sealed boxes, they must carry every box and open each one. DataFrames are the inventory, RDDs the sealed boxes.

Why the DataFrame version is faster

Take the sales job from the previous lesson. With the RDD, Spark sees three Python functions it cannot look inside, so it runs them as written, on every row. With the DataFrame, it sees a description: keep rows where amount > 0, group by country, sum amount, which it can rearrange, read less for, and compile. The lab below times both over 3 million rows: about 6.5 seconds against 0.35. Five things add up to that gap.

RDD versionDataFrame version
1. Data readEvery column of every rowOnly country and amount, and skips row groupsrow group: A block of rows inside a Parquet file. Its min and max statistics let readers skip blocks that cannot match a filter. Learn more → that cannot match
2. Where the code runsEach row goes to a Python worker and backEntirely in the JVM; Python only builds the plan
3. Row formatOne object per row, plus one per fieldCompact binary rows (Tungsten)
4. ExecutionOne function call per row per stepOne compiled loop for the whole stagestage: A group of steps Spark can run without moving data between machines. A new stage starts at every shuffle. Learn more →
5. Pre-aggregationPython objects combined in PythonBinary rows in a hash map, in generated code

1. Catalyst reads less data

Say sales is a ParquetParquet: A columnar file format: values of each column are stored together, so queries read only the columns they need. Learn more → table with 20 columns and 100 million rows, 10 GB on disk. sales.rdd has to turn every row into a full Python Row with all 20 fields before your first lambda runs, so Spark reads the whole 10 GB. The lambda then throws most of it away.

The DataFrame query tells CatalystCatalyst: Spark's query optimizer. It rewrites your DataFrame code into a faster equivalent plan before running it. Learn more → which columns it uses and what the filter is, so two things happen in the file scan itself. Column pruningcolumn pruning: Reading only the columns a query uses, which columnar files like Parquet make possible. Learn more →: Parquet stores each column separately, so reading 2 of 20 columns reads roughly a tenth of the bytes. Predicate pushdownpredicate pushdown: Applying a filter while reading files, so data that cannot match is skipped instead of read. Learn more →: amount > 0 is handed to the Parquet reader, which checks each row group's min/max statistics and skips groups that cannot match, then filters the rest before building rows. In the plan this shows up on the scan line:

From explain() of the DataFrame version

FileScan parquet [country#470,amount#471L] ...
  PushedFilters: [IsNotNull(amount), GreaterThan(amount,0)]
  ReadSchema: struct<country:string,amount:bigint>

2. No Python round trip per row

An RDD lambda in PySpark cannot run in the JVM. For every partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more →, the executorexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more → starts (or reuses) a Python worker process and streams the rows to it over a local socket: serialiseserialization: Turning objects into bytes so they can be sent over the network or stored, and back again. Learn more → them with pickle in the JVM, deserialise them into Python objects, call your function once per row, pickle the results, and send them back. With three lambdas over 100 million rows, that is hundreds of millions of Python function calls plus the pickling in both directions, which usually costs more than the calls themselves.

DataFrame functions such as F.col("amount") > 0 and F.sum are not Python code that runs on the data: they are instructions for building a plan. The plan runs in the JVM, and Python is not involved after the driverdriver: The process that runs your program, plans the work and sends tasks to executors. Learn more → submits it. This is why PySpark DataFrame code runs at the same speed as the same query in Scala or SQL, and why a single Python UDFUDF: User-defined function: your own Python function applied to each row. Flexible but much slower than built-in functions. Learn more → in the middle of a query brings the round trip back for that step.

3. Tungsten keeps rows in a compact binary format

In the JVM, an RDD of rows is an RDD of objects: each row is an object pointing to an array of field objects, a number is a boxed Long, a string is its own object with its own character array, and every object carries a header. A two-field row takes around 100 bytes spread across several objects. Billions of short-lived objects mean heavy garbage collection, which shows as GC time in the Spark UI.

DataFrames store rows in Tungsten's UnsafeRow format: one contiguous block of bytes with a null bitmap, 8 bytes per fixed-width field, and variable-length data such as strings at the end. The same row is a few dozen bytes in one block, often off the JVM heap. Operators read fields straight from those bytes, sorting compares bytes, and a shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → copies the bytes without serialising objects.

4. Whole-stage code generation

The classic way to run a query plan is the iterator model: each operator asks its child for the next row, does its work and passes the row up. That is several virtual function calls and a row hand-off per operator, per row. For a chain such as scan, filter, project and partial aggregate, Spark instead generates one Java method containing a single loop that does all four steps, compiles it at runtime, and lets the JVM's JIT turn it into tight machine code. Values stay in local variables (often CPU registers) instead of being written into intermediate rows.

In explain() output after a query has run, operators marked with the same *(1), *(2) are fused into one generated function; explain("codegen") prints the generated code. Python lambdas cannot be fused into that loop, which is another reason an RDD or UDF step stays slow.

5. Pre-aggregation on binary rows

Both versions shrink the data before the shuffle: reduceByKey combines per partition, and the DataFrame runs partial_sum per tasktask: The work for one partition in one stage, run on one CPU core. Learn more →, so each task sends a handful of rows instead of millions. The difference is how: reduceByKey calls your Python lambda per row and builds Python tuples, while partial_sum updates an off-heap hash map of binary rows inside the generated loop. (groupByKey skips the combine and ships every value: the classic RDD mistake.)

Why this matters: all five depend on Spark understanding the computation. One opaque step (df.rdd, a Python UDF, a map over rows) switches them off from that point. Prefer built-in functions; when Python is unavoidable, use pandas UDFs.

Try it yourself

Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.

Goal: Time the same aggregation written with RDDs and with DataFrames, on the same data.

ExplorePySpark · The same aggregation as an RDD and as a DataFrame, timed
import time
from pyspark.sql import functions as F

(spark.range(0, 3_000_000)
    .withColumn("country", (F.col("id") % 5).cast("string"))
    .withColumn("amount", F.col("id") % 100)
    .withColumn("note", F.lit("x" * 50))           # a wide column the query never needs
    .write.mode("overwrite").parquet("lab/rdd_vs_df/orders"))
orders = spark.read.parquet("lab/rdd_vs_df/orders")

t = time.time()
rdd_result = (orders.rdd                          # every row becomes a Python object
    .filter(lambda r: r.amount > 0)
    .map(lambda r: (r.country, r.amount))
    .reduceByKey(lambda a, b: a + b)
    .collect())
print(f"RDD: {time.time() - t:.2f}s")

t = time.time()
df_result = (orders.filter("amount > 0")
             .groupBy("country").agg(F.sum("amount")).collect())
print(f"DataFrame: {time.time() - t:.2f}s")
print("same answer:", sorted(rdd_result) == sorted(tuple(r) for r in df_result))

Output from a real run

RDD: 6.54s
DataFrame: 0.35s
same answer: True

What to notice:

  • Both give the same answer (same answer: True), but the DataFrame version was many times faster (about 0.4 s against 6.5 s here).
  • The RDD version turns every row into a Python object. The DataFrame version reads only the two columns it needs and sums inside the JVM.
  • To see why, run .explain() on the DataFrame query: look for PushedFilters, a two-column ReadSchema, and partial_sum before the shuffle.

Common mistakes

  • Converting to an RDD to do something a DataFrame can do — df.rdd.map(...) loses all optimisation and adds Python serialisation.
  • groupByKey followed by a sum — Ships every value over the network. reduceByKey or a DataFrame groupBy combines locally first.
  • A Python UDF in the middle of a DataFrame query — That step loses pushdown, pruning and code generation, like an RDD lambda. Prefer a built-in, or a pandas UDF.

Key takeaways

  • A DataFrame tells Spark what you want, so Catalyst can read less and plan better.
  • RDD lambdas and Python UDFs send every row to a Python worker and back.
  • Tungsten stores rows as compact bytes, and whole-stage code generation fuses operators into one loop.
  • One opaque step (df.rdd, a UDF, a map over rows) switches all of this off from that point on.

Interview prep

THE QUESTION

"Your PySpark job does df.rdd.map(lambda r: ...) and then a groupBy. It is slow. Why, and what do you change?"

df.rdd turns every row into a Python object and runs the lambda in a Python worker, pickling both ways, and Spark loses pruning, pushdown, Tungsten rows and code generation for that step. Rewrite it with built-in column functions so the query stays in the JVM; if Python is truly needed, use a pandas UDF (Arrow batches).

Avoid: "DataFrames are faster because they are newer" without naming what Spark can do with a DataFrame that it cannot do with an opaque function.

Follow-ups · answer out loud, then open

Follow-up"Does PySpark DataFrame code run slower than the same query in Scala?"
No, if it uses built-in functions: Python only builds the plan, which runs in the JVM. Python costs extra only for steps that run Python per row, such as RDD lambdas and Python UDFs.
Scenario"A colleague wrote a Python UDF to uppercase a column and strip spaces. What do you suggest?"
Replace it with F.upper(F.trim(col)): built-ins run in the JVM, keep code generation and never send rows to Python. If a UDF is really needed, a pandas UDF moves rows in Arrow batches.
Trap"reduceByKey makes the RDD version as fast as the DataFrame version."
It combines values before the shuffle, like partial aggregation, but the RDD still reads every column, builds a Python object per row and runs lambdas in Python.

Check yourself

3 questions

Why can Spark push a filter into the Parquet reader for a DataFrame but not for an RDD?

Show the answer

The DataFrame filter is a known expression; an RDD filter is an opaque function. Catalyst can only optimise what it can read.

Which RDD operation combines values on each executor before the shuffle?

Show the answer

reduceByKey. reduceByKey does map-side combining; groupByKey sends every value.

In explain() output, what do operators marked with the same *(1) have in common?

Show the answer

They are fused into one generated function. Whole-stage code generation compiles that chain of operators into a single loop.

Practise this

Interview problems on spark performance, graded on hidden tests

Keep going

Up next · How a job runs · lesson 4 of 5 · 7 min read
Partitions
The unit of parallelism in Spark: where partitions come from and why their number matters.

Related lessons

Previous: RDDs, DataFrames and Datasets

Primary sources: SQL, DataFrames and Datasets · Performance tuning