⚡️ Speed up function apply_function
by 1,957%
#71
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 1,957% (19.57x) speedup for
apply_function
insrc/numpy_pandas/dataframe_operations.py
⏱️ Runtime :
48.4 milliseconds
→2.35 milliseconds
(best of857
runs)📝 Explanation and details
The optimization replaces a manual row-by-row iteration with pandas' vectorized
map()
operation, resulting in a dramatic ~20x speedup.Key changes:
df.iloc[i][column]
access pattern: The original code usesdf.iloc[i][column]
inside a loop, which is extremely inefficient. Eachiloc
call triggers pandas' positional indexing machinery, creating significant overhead for every row access.df[column].map(func)
, which operates directly on the pandas Series using optimized C code paths rather than Python iteration.Why this is faster:
The original implementation has O(n) calls to
iloc
, each with substantial overhead for index resolution and type checking. The line profiler shows thatdf.iloc[i][column]
consumes 98% of the execution time (396ms out of 405ms total). In contrast,Series.map()
leverages pandas' internal optimizations and vectorized operations, processing the entire column at once with minimal per-element overhead.Performance characteristics by test case:
The optimization is most effective for medium to large datasets where the vectorization benefits outweigh the setup costs.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-apply_function-mdperii7
and push.