Skip to content

Commit

Permalink
[10.x] Refactored LazyCollection::take() to save memory (#48382)
Browse files Browse the repository at this point in the history
* refactor: stop using paththru in take method

* refactor: use ring buffer

* test: add negative limit test

* Revert "test: add negative limit test"

This reverts commit 601eb3b.

* Update src/Illuminate/Collections/LazyCollection.php

Co-authored-by: Joseph Silber <[email protected]>

---------

Co-authored-by: Joseph Silber <[email protected]>
  • Loading branch information
fuwasegu and JosephSilber authored Sep 18, 2023
1 parent 8e319c0 commit 9ac653d
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/Illuminate/Collections/LazyCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1421,7 +1421,21 @@ public function sortKeysUsing(callable $callback)
public function take($limit)
{
if ($limit < 0) {
return $this->passthru('take', func_get_args());
return new static(function () use ($limit) {
$limit = abs($limit);
$ringBuffer = [];
$position = 0;

foreach ($this as $key => $value) {
$ringBuffer[$position] = [$key, $value];
$position = ($position + 1) % $limit;
}

for ($i = 0, $end = min($limit, count($ringBuffer)); $i < $end; $i++) {
$pointer = ($position + $i) % $limit;
yield $ringBuffer[$pointer][0] => $ringBuffer[$pointer][1];
}
});
}

return new static(function () use ($limit) {
Expand Down

0 comments on commit 9ac653d

Please sign in to comment.