I wanted to know approximately how much overhead would result from building HTML tags using a tag class, vs Yii’s approach, where every tag builder is a static method.
Here’s the benchmark I wrote:
<?php
/*
Tag class vs static tag builder benchmark.
Run using apache bench from the command-line:
ab -n 1000 -c 10 http://test/sandbox/tagbench.php
*/
class Tag
{
private $_name;
private $_attr;
public function __construct($name, $attr=array())
{
$this->_name = $name;
$this->_attr = $attr;
}
public function __get($name)
{
return $this->_attr[$name];
}
public function __set($name, $value)
{
$this->_attr[$name] = $value;
}
public function __toString()
{
$attr = array();
foreach ($this->_attr as $name=>$value)
$attr[] = $name.'="'.$value.'"';
return "<{$this->_name} ".implode(' ',$attr)."/>";
}
}
class TagBuilder
{
public static function build($_name, $_attr=array())
{
$attr = array();
foreach ($_attr as $name=>$value)
$attr[] = $name.'="'.$value.'"';
return "<{$_name} ".implode(' ',$attr)."/>";
}
}
header('Content-type: text/plain');
for ($i=0; $i<1000; $i++)
{
// Comment out one version or the other before benchmarking.
echo new Tag('img', array('src'=>'http://test/image.png', 'width'=>123, 'height'=>456));
//echo TagBuilder::build('img', array('src'=>'http://test/image.png', 'width'=>123, 'height'=>456));
}
Measured result: the net overhead for the class-based version is 12%.
The advantages of using classes rather than static methods should be self-explanatory.
Do with this information what you will, I’m just putting that out there