Re: [RFC] array_search_range() function
| From: | Rowan Tommins [IMSoP] | Date: | Tue, 18 Aug 2026 21:52:35 +0000 |
| Subject: | Re: [RFC] array_search_range() function | ||
| References: | 1 2 3 4 5 6 7 8 9 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-132269@lists.php.net to get a copy of this message | ||
On 18 August 2026 19:32:08 BST, "سپهر محمودی" <sepehrphpr@gmail.com>
wrote:
>
>Your point about the polyfill was genuinely brilliant. It actually made
>
>me realize I was overcomplicating things. I went ahead and added a
>
>“Polyfill” section to the RFC
The polyfill you've added to the RFC uses array_slice, so has to copy part of the array into
new memory, and potentially iterate the array elements *twice* (once in array_slice, and again in
array_search).
The polyfill I included in my last email just loops over the array once, and stops when either a
match is found or the limit is reached. That's what I mean by "memory-efficient":
there is no need to make a copy of any part of the array.
That's basically the same algorithm that you'd need to implement in C, if you didn't
build a reusable ArraySliceIterator. (I note that the implementation you've linked doesn't
actually compile on any of the CI targets.)
There might be some performance gained just by looping in C rather than PHP, but the optimisations I
can see being more significant are taking advantage of the memory layout to jump quickly to the
initial offset:
- Since PHP 7, some PHP arrays are stored "packed" - that is, with the elements
sequentially in memory - so you can calculate the memory position of any element without iterating
the array at all. You can see that in action if you look up the source code for array_slice, and
both ArraySliceIterator and array_search_range could take advantage of it.
- For a hash-based array, you might still need to iterate to find the bucket with the initial
offset; but an ArraySliceIterator could then cache the memory location of that bucket, so that
iterating the same slice a second time was much faster.
None of this changes my opinion that the general-purpose ArraySliceIterator is a better feature for
the language than a single array_search_range function that doesn't build towards any future
scope.
Regards,
Rowan Tommins
[IMSoP]