Bug #72745 [Opn->Wfx]: reset() work much slower than foreach()
| From: | nikic@php.net | Date: | Sat, 06 Aug 2016 14:04:32 +0000 |
| Subject: | Bug #72745 [Opn->Wfx]: reset() work much slower than foreach() | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-203000@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=72745&edit=1
ID: 72745
Updated by: nikic@php.net
Reported by: sailormax at inbox dot lv
Summary: reset() work much slower than foreach()
-Status: Open
+Status: Wont fix
Type: Bug
Package: Arrays related
PHP Version: 7.0.9
Block user comment: N
Private report: N
New Comment:
I'm afraid there is not much we can do here. The problem you're running into is that
reset($arr2) is forced to actually perform the copy that was delayed in the $arr2 = $arr line. This
means you're copying the array on each iteration. The reason is that reset($arr2) actually
modifies $arr2 (it modifies the internal array pointer), while as of PHP 7 by-value foreach no
longer modifies $arr2 (it uses an external array pointer).
If possible, try to avoid using reset(), or alternatively don't copy the array beforehand.
Doing reset($arr) (without $arr2 = $arr) should give you non-quadratic performance.
Previous Comments:
------------------------------------------------------------------------
[2016-08-03 15:22:41] sailormax at inbox dot lv
Description:
------------
reset() work much slower than foreach() under PHP7
Looks like developers optimized foreach(), but forgot about reset(). Under PHP5 speeds are similar.
Test script:
---------------
$arr = array_fill(0, 10000, "a");
$ts = microtime(true);
$first_key = -1;
foreach ($arr as $k => $v)
{
$arr2 = $arr;
reset($arr2);
$first_key = key($arr2);
}
echo microtime(true)-$ts, "<br />\n";
echo $first_key, "<br />\n";
$ts = microtime(true);
$first_key = -1;
foreach ($arr as $k => $v)
{
$arr2 = $arr;
foreach ($arr2 as $k2 => $v2) break;
$first_key = $k2;
}
echo microtime(true)-$ts, "<br />\n";
echo $first_key, "<br />\n";
Expected result:
----------------
0.0011060237884521
0
0.0011060237884521
0
Actual result:
--------------
0.64054489135742
0
0.0011060237884521
0
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=72745&edit=1