Skip to content

Commit 943f84f

Browse files
authored
Merge pull request #18 from Innmind/optimize-takeEnd
Optimize the lazy Sequence::takeEnd()
2 parents 32ceacb + 4ad661a commit 943f84f

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

CHANGELOG.md

+6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Changelog
22

3+
## [Unreleased]
4+
5+
### Changed
6+
7+
- A lazy `Sequence::takeEnd()` no longer loads the whole sequence in memory, only the number of elements taken + 1.
8+
39
## 5.4.0 - 2024-05-29
410

511
### Added

src/Sequence/Lazy.php

+21-3
Original file line numberDiff line numberDiff line change
@@ -469,9 +469,27 @@ static function(RegisterCleanup $register) use ($values, $size): \Generator {
469469
*/
470470
public function takeEnd(int $size): Implementation
471471
{
472-
// this cannot be optimised as the whole generator needs to be loaded
473-
// in order to know the elements to drop
474-
return $this->load()->takeEnd($size);
472+
$values = $this->values;
473+
474+
return new self(
475+
static function(RegisterCleanup $register) use ($values, $size): \Generator {
476+
$buffer = [];
477+
$count = 0;
478+
479+
foreach ($values($register) as $value) {
480+
$buffer[] = $value;
481+
++$count;
482+
483+
if ($count > $size) {
484+
\array_shift($buffer);
485+
}
486+
}
487+
488+
foreach ($buffer as $value) {
489+
yield $value;
490+
}
491+
},
492+
);
475493
}
476494

477495
/**

0 commit comments

Comments
 (0)