Skip to content

Commit 9ac653d

Browse files
[10.x] Refactored LazyCollection::take() to save memory (#48382)
* 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 <contact@josephsilber.com> --------- Co-authored-by: Joseph Silber <contact@josephsilber.com>
1 parent 8e319c0 commit 9ac653d

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/Illuminate/Collections/LazyCollection.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1421,7 +1421,21 @@ public function sortKeysUsing(callable $callback)
14211421
public function take($limit)
14221422
{
14231423
if ($limit < 0) {
1424-
return $this->passthru('take', func_get_args());
1424+
return new static(function () use ($limit) {
1425+
$limit = abs($limit);
1426+
$ringBuffer = [];
1427+
$position = 0;
1428+
1429+
foreach ($this as $key => $value) {
1430+
$ringBuffer[$position] = [$key, $value];
1431+
$position = ($position + 1) % $limit;
1432+
}
1433+
1434+
for ($i = 0, $end = min($limit, count($ringBuffer)); $i < $end; $i++) {
1435+
$pointer = ($position + $i) % $limit;
1436+
yield $ringBuffer[$pointer][0] => $ringBuffer[$pointer][1];
1437+
}
1438+
});
14251439
}
14261440

14271441
return new static(function () use ($limit) {

0 commit comments

Comments
 (0)