프로그래밍 언어(must-have skills)/PHP
generator와 lazyCollection
트밀
2023. 10. 21. 16:22
genrator는 yield를 return한다. 이 개념을 이해해야 라라벨의 lazycollection을 이해할 수 있다.
generator
public function testXrangeAndRange(){
$exmaple1 = range(0, 1000000000); //value를 0부터 1000000000까지로 구성하는 배열을 생성하는 내장함수
//하지만 생성도중 메모리를 견디지 못한다.
foreach ($exmaple1 as $ab) {
echo $ab;
}
$exmplae2 = $this->xrange(0, 1000000000); //generator를 이용하면 메모리를 거의 사용안하고 iterate할 수 있다.
foreach ($exmplae2 as $ab) {
echo $ab;
}
}
private function xrange($start, $limit, $step = 1){
if ($start <= $limit) {
if ($step <= 0) {
throw new LogicException('Step must be positive');
}
for ($i = $start; $i <= $limit; $i += $step) {
yield $i;
}
} else {
if ($step >= 0) {
throw new LogicException('Step must be negative');
}
for ($i = $start; $i >= $limit; $i += $step) {
yield $i;
}
}