RFC: Add `final class Vector` to PHP
| From: | tyson andre | Date: | Fri, 17 Sep 2021 02:09:55 +0000 |
| Subject: | RFC: Add `final class Vector` to PHP | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-116048@lists.php.net to get a copy of this message | ||
Hi internals,
I've created a new RFC https://wiki.php.net/rfc/vector proposing to add
final class Vector to PHP.
PHP's native array type is rare among programming language in that it is used as
an associative map of values, but also needs to support lists of values.
In order to support both use cases while also providing a consistent internal array HashTable API to
the PHP's internals and PECLs, additional memory is needed to track keys
(https://www.npopov.com/2014/12/22/PHPs-new-hashtable-implementation.html - around twice as much as
is needed to just store the values due to needing space both for the string pointer and int key in a
Bucket, for non-reference counted values)).
Additionally, creating non-constant arrays will allocate space for at least 8 elements to make the
initial resizing more efficient, potentially wasting memory.
It would be useful to have an efficient variable-length container in the standard library for the
following reasons:
1. To save memory in applications or libraries that may need to store many lists of values and/or
run as a CLI or embedded process for long periods of time
(in modules identified as using the most memory or potentially exceeding memory limits in the
worst case)
(both in userland and in native code written in php-src/PECLs)
2. To provide a better alternative to ArrayObject and SplFixedArray for
use cases
where objects are easier to use than arrays - e.g. variable sized collections (For lists of
values) that can be passed by value to be read and modified.
3. To give users the option of stronger runtime guarantees that property, parameter, or return
values really contain a list of values without gaps, that array modifications don't introduce
gaps or unexpected indexes, etc.
Thoughts on Vector?
P.S. The functionality in this proposal can be tested/tried out at https://pecl.php.net/teds (under the class name
\Teds\Vector instead of \Vector).
(That is a PECL I created earlier this year for future versions of iterable proposals, common data
structures such as Vector/Deque, and less commonly used data structures that may be of use in future
work on implementing other data structures)
Thanks,
Tyson