On Mon, Mar 13, 2017 at 6:34 AM, Jesse Schalken <m...@jesseschalken.com> wrote:
> I noticed this commit > <https://github.com/facebook/hhvm/commit/4167d66fcfa81a1c2a1 > 9e853282fac968d9cd454> > recently in HHVM, which makes array_values() return the same array back if > it's packed instead of building a copy. > > My understanding is PHP 7 also has packed arrays like HHVM, and my reading > of PHP's array_values() implementation (here > <https://github.com/php/php-src/blob/c6982995504b6e21e8a5ade > 29cfb16a55196dc43/ext/standard/array.c#L4000>) > is that it always creates a copy of the array, even if it's packed. > > Would this be a worthwhile optimisation to make in PHP as well? > That would be nice if array_values() wouldn't reindex the array. But it does. $a = [12=> 'foo', 42 => 'bar']; // packed array $b = array_values($a); $b // [0 => 'foo', 42 => 'bar']; // keys have been changed and are not kept from source So, array_values() must allocate a new array, and fill it in with the values of source, because array_values() reindexes the source array from key 0 ; whatever was the original array. Note that the allocation is very light, in PHP 7, we allocate a full buffer at once , and not one buffer for each slot. The performance inpact of such an allocation is really really tiny. Julien.Pauli