note 125944 added to class.arrayiterator
| From: | mail at markuszeller dot com | Date: | Fri, 19 Mar 2021 17:55:59 +0000 |
| Subject: | note 125944 added to class.arrayiterator | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-219265@lists.php.net to get a copy of this message | ||
I recommend using ArrayIterator() only in the IteratorAggregate interface on behalf of memory usage.
When not used in that context, the array will be copied on creating a new ArrayIterator().
<?php
class Data implements IteratorAggregate
{
private array $array = [];
public function __construct()
{
for ($i = 0; $i < 1e5; $i++) $this->array[] = true;
}
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->array);
}
}
$data1 = new Data();
echo memory_get_usage(), PHP_EOL;
// 4610240
foreach($data1 as $data) {}
echo memory_get_usage(), PHP_EOL;
// 4610240
foreach($data1 as $data) {}
echo memory_get_usage(), PHP_EOL;
// 4610240
?>
Memory usage still stay the same.
Now create it without the IteratorAggregate interface.
<?php
$agg = [];
for ($i = 0; $i < 1e5; $i++) $agg[] = true;
echo memory_get_usage(), PHP_EOL;
// 8808720
$iterator1 = new ArrayIterator($agg);
echo memory_get_usage(), PHP_EOL;
// 13007328
$iterator2 = new ArrayIterator($agg);
echo memory_get_usage(), PHP_EOL;
// 17205936
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.246 (proxied: 2003:ed:8f12:5e39:d11:cc02:c2e8:1d8f)
----
Manual Page -- http://php.net/manual/en/class.arrayiterator.php
Edit -- https://master.php.net/note/edit/125944
Del: integrated -- https://master.php.net/note/delete/125944/integrated
Del: useless -- https://master.php.net/note/delete/125944/useless
Del: bad code -- https://master.php.net/note/delete/125944/bad+code
Del: spam -- https://master.php.net/note/delete/125944/spam
Del: non-english -- https://master.php.net/note/delete/125944/non-english
Del: in docs -- https://master.php.net/note/delete/125944/in+docs
Del: other reasons-- https://master.php.net/note/delete/125944
Reject -- https://master.php.net/note/reject/125944
Search -- https://master.php.net/manage/user-notes.php