Skip to content

Commit

Permalink
Speeding up each() by unwrapping uneeded nested collections first
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Jan 6, 2015
1 parent 9ee1eab commit a9aff86
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
6 changes: 5 additions & 1 deletion src/Collection/CollectionTrait.php
Expand Up @@ -46,7 +46,11 @@ trait CollectionTrait
*/
public function each(callable $c)
{
foreach ($this as $k => $v) {
$iterator = $this;
while (get_class($iterator) === 'Cake\Collection\Collection') {
$iterator = $iterator->getInnerIterator();
}
foreach ($iterator as $k => $v) {
$c($v, $k);
}
return $this;
Expand Down
10 changes: 9 additions & 1 deletion src/Collection/Iterator/ReplaceIterator.php
Expand Up @@ -30,6 +30,13 @@ class ReplaceIterator extends Collection
*/
protected $_callback;

/**
* A reference to the internal iterator this object is wrapping.
*
* @var \Iterator
*/
protected $_innerIterator;

/**
* Creates an iterator from another iterator that will modify each of the values
* by converting them using a callback function.
Expand All @@ -45,6 +52,7 @@ public function __construct($items, callable $callback)
{
$this->_callback = $callback;
parent::__construct($items);
$this->_innerIterator = $this->getInnerIterator();
}

/**
Expand All @@ -56,6 +64,6 @@ public function __construct($items, callable $callback)
public function current()
{
$callback = $this->_callback;
return $callback(parent::current(), $this->key(), $this->getInnerIterator());
return $callback(parent::current(), $this->key(), $this->_innerIterator);
}
}

0 comments on commit a9aff86

Please sign in to comment.