Improve performance of Arr::dot method - 300x in some cases #55495
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.
Array::dot Method Performance Optimization
Overview
This PR optimizes the
Arr::dot()
method, replacing the recursive implementation with a closure-based iterative approach. The optimization significantly improves performance when flattening large nested arrays, which is particularly beneficial for Laravel's validator when processing large datasets.Optimization Details
The original implementation used recursive
array_merge()
calls, which can lead to O(n²) behavior for large arrays:The optimized implementation uses a nested closure with references to avoid the expensive recursive
array_merge()
calls:Benchmark Results
Benchmarks were performed on arrays of different sizes, simulating real-world validation scenarios. Each benchmark ran 5 iterations and recorded the average execution time.
Testing Environment
Test Data Structure
The benchmark used nested arrays similar to those processed by Laravel's validator:
Performance Comparison
Memory Usage
Memory consumption remained consistent between the original and optimized implementations, showing no additional memory overhead.
Impact on Large Datasets
The performance improvement is particularly significant for large datasets. As demonstrated in the benchmark, processing a 10,000-item array improved from over 3.5 seconds to just 10.6 milliseconds - an improvement of 99.7%.
This optimization addresses the performance issues reported in #49375, where users experienced significant slowdowns when validating large datasets with wildcard rules.
Testing Methodology
Conclusion
The optimized
Arr::dot()
method provides substantial performance improvements for large arrays while maintaining identical functionality. This optimization benefits any Laravel feature that uses dot notation to work with nested arrays, particularly the validator when processing large datasets.The changes are non-breaking and fully backward compatible with the existing API.