본문 바로가기

프로그래밍 언어(must-have skills)/PHP

generator와 lazyCollection

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;
                }
            }

'프로그래밍 언어(must-have skills) > PHP' 카테고리의 다른 글

라라벨 큐 체험기  (0) 2023.09.13
php 벤치마크 사이트 추천 -The PHP Benchmark  (0) 2023.06.01
__call method  (0) 2023.04.29
[라라벨] laravel-debugbar  (0) 2023.03.07
[문법]PHP foreach 사용법  (0) 2023.02.11