Re: Request for couple memory optimized array improvements
| From: | John Bafford | Date: | Mon, 31 Aug 2020 21:50:21 +0000 |
| Subject: | Re: Request for couple memory optimized array improvements | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-111754@lists.php.net to get a copy of this message | ||
Hi Riikka,
> On Aug 31, 2020, at 14:13, Riikka Kalliomäki <riikka.kalliomaki@riimu.net> wrote:
>
> A common pattern that I've seen that could dearly use PHP internal
> optimization, if possible, would be:
>
> foreach (array_keys($array) as $key) {
> }
I have a draft RFC (https://wiki.php.net/rfc/foreach_void) and patch
(https://github.com/jbafford/php-src/tree/foreachvoid against php 7.0, I think) that helps with
this, by allowing the following syntax:
foreach($iterable as $key => void) { ... }
This would iterate over the keys of the iterable, and does not retrieve the values at all.
In theory, this should be a general performance win any time one needs to iterate over only the keys
of an iterable, because it does not require the use of an O(n) iteration and building of the array
that array_keys() would, plus it works on non-array types (such as generators or iterators). It also
is more performant than foreach($iterable as $key => $_) {}, because it omits the opcode that
instructs the engine to retrieve the value. (Presumably, a future direction could include using this
request to inform generators or iterators to only return keys, and not values, which could further
improve performance, especially if value generation is expensive. But that is out of scope for this
RFC.)
If this is something we'd like for PHP 8.1 and there are no major objections to the idea, then
after 8.0 is released, I can move the RFC out of Draft and into Under Discussion, and presuming a
vote passes, I'll update the patch as necessary to work against 8.0. But my time is limited and
I'm not willing to put further time into the code unless an RFC vote passes.
Thoughts anyone?
-John