Commit a8cc04dc315 for php.net
commit a8cc04dc31546d0fc0723adf44bb82f6f462ea4e
Author: Weilin Du <108666168+LamentXU123@users.noreply.github.com>
Date: Wed Mar 25 01:40:47 2026 +0800
Optimize JSON pretty print indentation performance (GH-21474)
Grow the string buffer in advance, avoiding repeated reallocations for each indentation level.
diff --git a/UPGRADING b/UPGRADING
index 113258ebbd3..b7b160820bb 100644
--- a/UPGRADING
+++ b/UPGRADING
@@ -252,6 +252,8 @@ PHP 8.6 UPGRADE NOTES
- JSON:
. Improve performance of encoding arrays and objects.
+ . Improved performance of indentation generation in json_encode()
+ when using PHP_JSON_PRETTY_PRINT.
- Standard:
. Improved performance of array_fill_keys().
diff --git a/ext/json/json_encoder.c b/ext/json/json_encoder.c
index 186485c05c6..d84917e95c7 100644
--- a/ext/json/json_encoder.c
+++ b/ext/json/json_encoder.c
@@ -54,6 +54,7 @@ static inline void php_json_pretty_print_char(smart_str *buf, int options, char
static inline void php_json_pretty_print_indent(smart_str *buf, int options, const php_json_encoder *encoder) /* {{{ */
{
if (options & PHP_JSON_PRETTY_PRINT) {
+ smart_str_alloc(buf, encoder->depth * 4, 0);
for (int i = 0; i < encoder->depth; ++i) {
smart_str_appendl(buf, " ", 4);
}