php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #79421 foreach (array_keys($arr) as $k) is slow
Submitted: 2020-03-27 19:50 UTC Modified: 2021-10-18 15:51 UTC
From: michael dot vorisek at email dot cz Assigned: cmb (profile)
Status: Duplicate Package: Performance problem
PHP Version: 7.4.4 OS:
Private report: No CVE-ID: None
 [2020-03-27 19:50 UTC] michael dot vorisek at email dot cz
Description:
------------
This is a feature request to optimize:

foreach (array_keys($arr) as $k) {}

instead of building array of keys optimize this in PHP internally to behave like:

foreach ($arr as $k => $ignore) {}

It is important to optimize it as foreach on keys is very commonly used.


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2020-04-10 07:00 UTC] alexinbeijing at gmail dot com
Interestingly, benchmarking shows that the 2nd form of the code you show here is actually *slower* than the 1st.

I don't know if foreach(array_keys(...) as ...) has already been optimized internally, but in any case, it doesn't seem that this suggested optimization is necessary. Recommend this ticket can be closed.
 [2020-04-10 18:43 UTC] michael dot vorisek at email dot cz
As long as iterate thru the whole dataset, otherwise it can be orders of magnitude slower.

$c = 20000;

// create test array
$arr = [];
for ($i = 0; $i < 1000; $i++) {
    $arr[$i . 'x'] = $i . 'y'; // use sting keys, they may be slower than numeric ones
}

$t = microtime(true);
for ($i = 0; $i < $c; $i++) {
    foreach ($arr as $k => $ignore) {
        $u = $k . '.'; // use key
        break;
    }
}
var_dump(round(microtime(true) - $t, 6));

$t = microtime(true);
for ($i = 0; $i < $c; $i++) {
    foreach (array_keys($arr) as $k) {
        $u = $k . '.'; // use key
        break;
    }
}
var_dump(round(microtime(true) - $t, 6));
 [2021-10-18 15:51 UTC] cmb@php.net
-Status: Open +Status: Duplicate -Assigned To: +Assigned To: cmb
 [2021-10-18 15:51 UTC] cmb@php.net
Closing as duplicate of bug #77532.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 19 17:01:30 2024 UTC