[php-src] PR #21474: Optimize JSON pretty print indentation performance
| From: | LamentXU123 | Date: | Fri, 20 Mar 2026 11:20:52 +0000 |
| Subject: | [php-src] PR #21474: Optimize JSON pretty print indentation performance | ||
| Groups: | php.git-pulls | ||
| Request: | Send a blank email to git-pulls+get-35275@lists.php.net to get a copy of this message | ||
Pull Request: https://github.com/php/php-src/pull/21474
Author: LamentXU123
This PR optimizes the
php_json_pretty_print_indent function in the JSON extension to
improve performance when encoding structures with JSON_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_appendl calls from O(N) to exactly 1. This significantly reduces function
call overhead and improves CPU performance during json_encode with
JSON_PRETTY_PRINT, especially for deeply nested data.