In the last session we had an introduction about generators, today we will see difference between generators and the iterator object in this Generators and iterator objects tutorial.
- An iterator is an object which is used to traverse a container like lists.
- Iterators are often provided by the containers interface.
- An iterator traverses throughout the container and also gives access to the data in it.
- But implementing iterator is very complex and time consuming.
- Whereas generators with its generator function and yield keyword has made this task very simple and economic in time.
- Generators are forward only but iterators can traverse through both the sides.
- The code written for generators is basically very less as compared to iterators.
- Come on let us see an example code to compare both iterators and generators.
- For this, create a new folder named generator_iterator in the htdocs folder in xampp folder. Open a new notepad++ document and save it as index.php in this newly created generator_iterator folder.
- First we will write code for iterator in index.php file:
<?php
class display implements iterator
{
$v=1;
$l=0;
public function __construct($e)
{
$this->l=$e;
}
public function rewind()
{
$this->value=$v;
}
public function current()
{
return $this->value;
}
public function key()
{
return $this>value;
}
public function next()
{
return($this->value += $this->v);
}
public function valid()
{
return $this->value<=$this->l;
}
}
echo "<h1>Numbers upto the given range are:</h1>";
$nos=new display(100);
foreach($nos as $n)
{
echo $n."<br>";
}
}
?>
<?php
function nos($l)
{
for($i=1;$i<=$l;$i++)
{
yield $i;
}
return;
}
echo "<h1>Numbers upto the given range are:</h1>";
foreach(nos(10) as $n)
{
echo $n."<br>";
}
?>
Thus we see that as the generator object maintains its state and generate a new value on each iteration with less use of memory, it is very economic to use in the suitable conditions although not useful in day to day tasks.