[12.x] Optimize MessageBag::all() #57406
Closed
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.
Optimize MessageBag::all() performance from O(n²) to O(n)
Summary
This PR optimizes the
MessageBag::all()method by replacing the O(n²)array_merge()approach with O(n) direct array building, resulting in significant performance improvements for applications with large validation error sets.Problem
The current implementation uses
array_merge()in a loop, which creates a new array and copies all previous elements on each iteration:This results in O(n²) complexity where n is the total number of messages.
Solution
Replace the
array_merge()approach with direct array building:This reduces complexity to O(n) while maintaining identical behavior.
MessageBag::all() Performance Benchmark
Benchmark Code (Click to expand)
You can reproduce these results with the following code:
Real-World Impact
This optimization particularly benefits:
Testing
Backward Compatibility
This change is fully backward compatible with no breaking changes to the public API or behavior.