An Argument Against the Traditional Iterator

Attached are two scripts that contain code for two styles of iterator. One is the traditional Iterator, and the other is what I'll call an IterObj. The Iterator requres separation of the iterator object and the objects that are returned by the iterator.

The IterObj combines the two parts into one. It's an object that also implements the iterator interface. It's "bad" OO design practice, because you're combining concerns, and also possibly creating repetitive code.

Test results indicate that the IterObj takes 1/18th the time to loop over the arrays. So, on a computer that's creating a bunch of iterators and objects, using the IterObj style can help improve performance.

That said, the performance cost of iteration is probably negligible compared to the cost of a database query or disk access.

If you think of what the traditional iterator style costs in additional database queries, it's pretty high. (See the link.) An IterObj that integrates calls to the database can iterate over the results of a single query.

The main tradeoff is memory -- the database result is held in memory on the database server until the iterator finishes. What you save in CPU and memory on the web server, you pay for on the database server. If they're on the same machine, it may not be an issue.

Code follows for each:

class Obj {
	function __construct($id)
	{
		$this->id = $id;
	}
}

class Iter {
	function __construct( $array, $objName )
	{
		$this->list = $array;
		$this->__objName = $objName;
	}
	function next()
	{
		$id = current($this->list);
		next($this->list);
		if ($id)
			return new $this->__objName($id);
		else
			return Null;
	}
}

And the IterObj type:

class IterObj {
	function __construct( $ar )
	{
		$this->list = $ar;
		$this->id = current($this->list);
	}
	function next()
	{
		$this->id = next($this->list);
	}
	function rewind()
	{
		reset($this->list);
		$this->id = current($this->list);
	}
}

http://www.devarticles.com/c/a/PHP/Building-an-Iterator-with-PHP/1/

AttachmentSize
test.iter_.php.txt579 bytes
test.iterobj.php.txt486 bytes