Iterator 객체와 Generators 비교

generator의 주요 장점은 단순성입니다. Iterator 클래스를 구현하는 것과 비교하여 훨씬 적은 상용구 코드를 작성해야 하며 코드는 일반적으로 훨씬 더 읽기 쉽습니다. 예를 들어 다음 함수와 클래스는 동일합니다.

                  
<?php
function getLinesFromFile($fileName) {
    if (!$fileHandle = fopen($fileName, 'r')) {
        return;
    }

    while (false !== $line = fgets($fileHandle)) {
        yield $line;
    }

    fclose($fileHandle);
}

// versus...

class LineIterator implements Iterator {
    protected $fileHandle;

    protected $line;
    protected $i;

    public function __construct($fileName) {
        if (!$this->fileHandle = fopen($fileName, 'r')) {
            throw new RuntimeException('Couldn\'t open file "' . $fileName . '"');
        }
    }

    public function rewind() {
        fseek($this->fileHandle, 0);
        $this->line = fgets($this->fileHandle);
        $this->i = 0;
    }

    public function valid() {
        return false !== $this->line;
    }

    public function current() {
        return $this->line;
    }

    public function key() {
        return $this->i;
    }

    public function next() {
        if (false !== $this->line) {
            $this->line = fgets($this->fileHandle);
            $this->i++;
        }
    }

    public function __destruct() {
        fclose($this->fileHandle);
    }
}
?>
                  
                

그러나 이러한 유연성에는 대가가 따릅니다. 제너레이터는 순방향 전용 반복기이며 반복이 시작되면 되돌릴 수 없습니다. 이것은 또한 동일한 생성기가 여러 번 반복될 수 없음을 의미합니다. 생성기는 생성기 함수를 다시 호출하여 다시 빌드해야 합니다.


기타