From 1803f20c42736246f401342f6f1b7f2f3b2affdb Mon Sep 17 00:00:00 2001 From: Niels Dossche <7771979+nielsdos@users.noreply.github.com> Date: Sun, 20 Jul 2025 15:55:59 +0200 Subject: [PATCH 1/2] Avoid modulo operation in loop in array_chunk For this benchmark: ```php $length = 25; for ($i=0;$i<1000;$i++) array_chunk(range(0, 10000), $length); ``` On an i7-4790, length=25 speeds up by 1.8x and length=1 by 1.27x. On an i7-1185G7, length=25 speeds up by 1.08x and length=1 by 1.02x. --- ext/standard/array.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ext/standard/array.c b/ext/standard/array.c index 522e7f715acb7..6de78c3900a93 100644 --- a/ext/standard/array.c +++ b/ext/standard/array.c @@ -7046,9 +7046,10 @@ PHP_FUNCTION(array_chunk) /* If reached the chunk size, add it to the result array, and reset the * pointer. */ - if (!(++current % size)) { + if (++current == size) { add_next_index_zval(return_value, &chunk); ZVAL_UNDEF(&chunk); + current = 0; } } ZEND_HASH_FOREACH_END(); From 3931badc0b9b40d3d4e25595f5cd9c2ab7566b0f Mon Sep 17 00:00:00 2001 From: Niels Dossche <7771979+nielsdos@users.noreply.github.com> Date: Sun, 20 Jul 2025 16:26:42 +0200 Subject: [PATCH 2/2] Allocate array eagerly in array_chunk By preallocating it as a packed array, we save the initial initialization overhead. Gives a few extra percentage points improvement. --- ext/standard/array.c | 1 + 1 file changed, 1 insertion(+) diff --git a/ext/standard/array.c b/ext/standard/array.c index 6de78c3900a93..5f2e34fdd545e 100644 --- a/ext/standard/array.c +++ b/ext/standard/array.c @@ -7023,6 +7023,7 @@ 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);