symfony / polyfill

PHP polyfills

Home Page:https://symfony.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[improvement] array_key_last

donaldinou opened this issue · comments

I've note some minor performance issues on array_key_last.
A good work has been done on this pull request #150

I think we could do a little better with array_slice instead of using both end and key function.

Here I come with benchmarks

function array_key_last(array $array) {
    return (!empty($array)) ? key(array_slice($array, -1, 1, true)) : null;
}

note: the proposed version by @donaldinou has also better performance from a memory point of view:

because of Copy On Write, and because the version in #150 uses end, the array is duplicated in memory.
but the version of @donaldinou don't alter the original array

function array_key_last2(array $array)
{
    end($array);
    return key($array);
}

$a = array_fill(0, 1024*1024, str_repeat('x', 1024*1024));
var_dump(memory_get_peak_usage(true)); // int(35655680)
array_key_last2($a);
var_dump(memory_get_peak_usage(true)); // int(69214208)

vs

function array_key_last2(array $array)
{
    return (!empty($array)) ? key(array_slice($array, -1, 1, true)) : null;
}

$a = array_fill(0, 1024*1024, str_repeat('x', 1024*1024));
var_dump(memory_get_peak_usage(true)); // int(35655680)
array_key_last2($a);
var_dump(memory_get_peak_usage(true)); // int(35655680)

PR welcome.
Note that there is no need to use empty() so that it should be:
return $array ? key(array_slice($array, -1, 1, true)) : null;