note 112482 added to language.generators.comparison

From: Date: Thu, 20 Jun 2013 19:45:44 +0000
Subject: note 112482 added to language.generators.comparison
Groups: php.notes 
Request: Send a blank email to php-notes+get-195305@lists.php.net to get a copy of this message
This hardly seems a fair comparison between the two examples, size-for-size. As noted, generators are forward-only, meaning that it should be compared to an iterator with a dummy rewind function defined. Also, to be fair, since the iterator throws an exception, shouldn't the generator example also throw the same exception? The code comparison would become more like this: <?php function getLinesFromFile($fileName) { if (!$fileHandle = fopen($fileName, 'r')) { throw new RuntimeException('Couldn\'t open file "' . $fileName . '"'); } 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() { } 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); } } ?> The generator is still obviously much shorter, but this seems a more reasonable comparison. ---- Server IP: 69.147.83.199 Probable Submitter: 76.250.104.182 ---- Manual Page -- http://php.net/manual/en/language.generators.comparison.php Edit -- https://master.php.net/note/edit/112482 Del: integrated -- https://master.php.net/note/delete/112482/integrated Del: useless -- https://master.php.net/note/delete/112482/useless Del: bad code -- https://master.php.net/note/delete/112482/bad+code Del: spam -- https://master.php.net/note/delete/112482/spam Del: non-english -- https://master.php.net/note/delete/112482/non-english Del: in docs -- https://master.php.net/note/delete/112482/in+docs Del: other reasons-- https://master.php.net/note/delete/112482 Reject -- https://master.php.net/note/reject/112482 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#195305) next »