[SPARK-53939][PYTHON] Use batch.num_columns instead of len(batch.columns)

### What changes were proposed in this pull request?

Use `batch.num_columns` instead of `len(batch.columns)` in `ArrowStreamUDFSerializer`.

### Why are the changes needed?

`len(batch.columns)` has a performance overhead compared with `batch.num_columns`.
It should be avoided.

<details>
<summary>benchmark_column_count_access</summary>

```python
import pyarrow as pa
import time
import numpy as np

def benchmark_column_count_access():
    # Create test data with varying number of columns
    column_counts = [10, 50, 100, 500, 1000]
    iterations = 1_000_000

    print("PyArrow RecordBatch Column Count Access Benchmark")
    print("=" * 70)
    print(f"Iterations: {iterations:,}")
    print()

    for num_cols in column_counts:
        # Create a RecordBatch with the specified number of columns
        arrays = [pa.array(np.random.rand(100)) for _ in range(num_cols)]
        names = [f"col_{i}" for i in range(num_cols)]
        batch = pa.record_batch(arrays, names=names)

        # Benchmark len(batch.columns)
        start = time.perf_counter()
        for _ in range(iterations):
            _ = len(batch.columns)
        time_len_columns = time.perf_counter() - start

        # Benchmark batch.num_columns
        start = time.perf_counter()
        for _ in range(iterations):
            _ = batch.num_columns
        time_num_columns = time.perf_counter() - start

        # Calculate speedup
        speedup = time_len_columns / time_num_columns

        print(f"Columns: {num_cols:>4}")
        print(f"  len(batch.columns):  {time_len_columns:.4f}s")
        print(f"  batch.num_columns:   {time_num_columns:.4f}s")
        print(f"  Speedup:             {speedup:.2f}x")
        print(f"  Difference:          {(time_len_columns - time_num_columns)*1000:.2f}ms")
        print()
```

</details>

```
PyArrow RecordBatch Column Count Access Benchmark
======================================================================
Iterations: 1,000,000

Columns:   10
  len(batch.columns):  4.0907s
  batch.num_columns:   0.0215s
  Speedup:             190.38x
  Difference:          4069.23ms

Columns:   50
  len(batch.columns):  19.7623s
  batch.num_columns:   0.0212s
  Speedup:             932.47x
  Difference:          19741.09ms

Columns:  100
  len(batch.columns):  39.7946s
  batch.num_columns:   0.0191s
  Speedup:             2088.70x
  Difference:          39775.53ms

Columns:  500
  len(batch.columns):  205.2582s
  batch.num_columns:   0.0210s
  Speedup:             9783.63x
  Difference:          205237.24ms

Columns: 1000
  len(batch.columns):  447.2963s
  batch.num_columns:   0.0234s
  Speedup:             19085.39x
  Difference:          447272.90ms
```

### Does this PR introduce _any_ user-facing change?

No.

### How was this patch tested?

The existing tests should pass.

### Was this patch authored or co-authored using generative AI tooling?

No.

Closes #52639 from ueshin/issues/SPARK-53939/num_columns.

Authored-by: Takuya Ueshin <ueshin@databricks.com>
Signed-off-by: Hyukjin Kwon <gurwls223@apache.org>
1 file changed
tree: ea71d8fce0362f7159424b7059f71b3b979df166
  1. .github/
  2. .mvn/
  3. assembly/
  4. bin/
  5. binder/
  6. build/
  7. common/
  8. conf/
  9. connector/
  10. core/
  11. data/
  12. dev/
  13. docs/
  14. examples/
  15. graphx/
  16. hadoop-cloud/
  17. launcher/
  18. licenses/
  19. licenses-binary/
  20. mllib/
  21. mllib-local/
  22. project/
  23. python/
  24. R/
  25. repl/
  26. resource-managers/
  27. sbin/
  28. sql/
  29. streaming/
  30. tools/
  31. ui-test/
  32. .asf.yaml
  33. .gitattributes
  34. .gitignore
  35. .nojekyll
  36. CONTRIBUTING.md
  37. LICENSE
  38. LICENSE-binary
  39. NOTICE
  40. NOTICE-binary
  41. pom.xml
  42. README.md
  43. scalastyle-config.xml
README.md

Apache Spark

Spark is a unified analytics engine for large-scale data processing. It provides high-level APIs in Scala, Java, Python, and R (Deprecated), and an optimized engine that supports general computation graphs for data analysis. It also supports a rich set of higher-level tools including Spark SQL for SQL and DataFrames, pandas API on Spark for pandas workloads, MLlib for machine learning, GraphX for graph processing, and Structured Streaming for stream processing.

GitHub Actions Build PySpark Coverage PyPI Downloads

Online Documentation

You can find the latest Spark documentation, including a programming guide, on the project web page. This README file only contains basic setup instructions.

Build Pipeline Status

BranchStatus
masterGitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
branch-4.0GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
GitHub Actions Build
branch-3.5GitHub Actions Build
GitHub Actions Build

Building Spark

Spark is built using Apache Maven. To build Spark and its example programs, run:

./build/mvn -DskipTests clean package

(You do not need to do this if you downloaded a pre-built package.)

More detailed documentation is available from the project site, at “Building Spark”.

For general development tips, including info on developing Spark using an IDE, see “Useful Developer Tools”.

Interactive Scala Shell

The easiest way to start using Spark is through the Scala shell:

./bin/spark-shell

Try the following command, which should return 1,000,000,000:

scala> spark.range(1000 * 1000 * 1000).count()

Interactive Python Shell

Alternatively, if you prefer Python, you can use the Python shell:

./bin/pyspark

And run the following command, which should also return 1,000,000,000:

>>> spark.range(1000 * 1000 * 1000).count()

Example Programs

Spark also comes with several sample programs in the examples directory. To run one of them, use ./bin/run-example <class> [params]. For example:

./bin/run-example SparkPi

will run the Pi example locally.

You can set the MASTER environment variable when running examples to submit examples to a cluster. This can be spark:// URL, “yarn” to run on YARN, and “local” to run locally with one thread, or “local[N]” to run locally with N threads. You can also use an abbreviated class name if the class is in the examples package. For instance:

MASTER=spark://host:7077 ./bin/run-example SparkPi

Many of the example programs print usage help if no params are given.

Running Tests

Testing first requires building Spark. Once Spark is built, tests can be run using:

./dev/run-tests

Please see the guidance on how to run tests for a module, or individual tests.

There is also a Kubernetes integration test, see resource-managers/kubernetes/integration-tests/README.md

A Note About Hadoop Versions

Spark uses the Hadoop core library to talk to HDFS and other Hadoop-supported storage systems. Because the protocols have changed in different versions of Hadoop, you must build Spark against the same version that your cluster runs.

Please refer to the build documentation at “Specifying the Hadoop Version and Enabling YARN” for detailed guidance on building for a particular distribution of Hadoop, including building for particular Hive and Hive Thriftserver distributions.

Configuration

Please refer to the Configuration Guide in the online documentation for an overview on how to configure Spark.

Contributing

Please review the Contribution to Spark guide for information on how to get started contributing to the project.