Optimize JSON pretty print indentation performance#21474
Open
LamentXU123 wants to merge 3 commits intophp:masterfrom
Open
Optimize JSON pretty print indentation performance#21474LamentXU123 wants to merge 3 commits intophp:masterfrom
LamentXU123 wants to merge 3 commits intophp:masterfrom
Conversation
mvorisek
reviewed
Mar 20, 2026
Contributor
Could you give some before/after numbers? |
Contributor
Author
Sure do, but maybe tomorrow. I think this is a pretty obvious optimization so I don't do this initially |
Member
|
A short benchmark would be appreciated. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
This PR optimizes the
php_json_pretty_print_indentfunction in the JSON extension to improve performance when encoding structures withJSON_PRETTY_PRINT.When I was reading this, I found that now, the indentation logic used a for loop to append spaces in increments of 4 characters per depth level. For a JSON structure with a depth of N, this resulted in N consecutive calls to
smart_str_appendl. This approach introduces unnecessary overhead due to repeated function calls.So I think I would introduce this space-time optimization to add a static constant string of pre-allocated spaces. For almost all typical JSON depths, this reduces the number of
smart_str_appendlcalls from O(N) to exactly 1. This significantly reduces function call overhead and improves CPU performance duringjson_encodewithJSON_PRETTY_PRINT, especially for deeply nested data.