From 97e3605abd9a00ae3b94f22de86c64b9eca2961a Mon Sep 17 00:00:00 2001 From: Niels Dossche <7771979+ndossche@users.noreply.github.com> Date: Sat, 8 Nov 2025 13:28:29 +0100 Subject: [PATCH 1/2] standard: Simplify array_chunk() Shrinks the code size from 682 to 601 bytes on x86-64 with GCC 15.2.1. Does not make a difference in performance, at least on my i7-4790. I also tried specialising the pack logic like I did with str_split(), but that is a hit or miss in performance improvement depending on the length. It seems that the instruction cache is become too full, and the fact that add_next_index_zval() and zend_hash_next_index_insert() use the same code internally is beneficial. --- ext/standard/array.c | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/ext/standard/array.c b/ext/standard/array.c index 0ef700f14a74..6e879e475f93 100644 --- a/ext/standard/array.c +++ b/ext/standard/array.c @@ -7053,8 +7053,7 @@ PHP_FUNCTION(array_chunk) if (size > num_in) { if (num_in == 0) { - RETVAL_EMPTY_ARRAY(); - return; + RETURN_EMPTY_ARRAY(); } size = num_in; } @@ -7062,12 +7061,11 @@ PHP_FUNCTION(array_chunk) array_init_size(return_value, (uint32_t)(((num_in - 1) / size) + 1)); zend_hash_real_init_packed(Z_ARRVAL_P(return_value)); - ZVAL_UNDEF(&chunk); - ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(input), num_key, str_key, entry) { /* If new chunk, create and initialize it. */ - if (Z_TYPE(chunk) == IS_UNDEF) { + if (current == 0) { array_init_size(&chunk, (uint32_t)size); + add_next_index_zval(return_value, &chunk); } /* Add entry to the chunk, preserving keys if necessary. */ @@ -7085,16 +7083,9 @@ PHP_FUNCTION(array_chunk) /* If reached the chunk size, add it to the result array, and reset the * pointer. */ if (++current == size) { - add_next_index_zval(return_value, &chunk); - ZVAL_UNDEF(&chunk); current = 0; } } ZEND_HASH_FOREACH_END(); - - /* Add the final chunk if there is one. */ - if (Z_TYPE(chunk) != IS_UNDEF) { - add_next_index_zval(return_value, &chunk); - } } /* }}} */ From a9e8a8bf0ce94e452d9e0c55f648cacc064b9c7d Mon Sep 17 00:00:00 2001 From: Niels Dossche <7771979+ndossche@users.noreply.github.com> Date: Sat, 8 Nov 2025 17:32:27 +0100 Subject: [PATCH 2/2] [ci skip] comment --- ext/standard/array.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/ext/standard/array.c b/ext/standard/array.c index 6e879e475f93..7aba89106d1f 100644 --- a/ext/standard/array.c +++ b/ext/standard/array.c @@ -7080,8 +7080,6 @@ PHP_FUNCTION(array_chunk) } zval_add_ref(entry); - /* If reached the chunk size, add it to the result array, and reset the - * pointer. */ if (++current == size) { current = 0; }