Class-based vs static methods for HTML tag builders

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 :slight_smile:

edit:

I have run your test with a 5000 loop and

  • through static: 0.27240800857544

  • through class based method: 0.36429977416992

So by your measurement, a 33% overhead - I wonder why the overhead on your system is so much higher than on mine?

Did you change anything besides the number of loops before running your test?

No mindplay,

I was very curious when you post this info as I am building extensions to display adaptive Tags to my CMS style and you made me wonder. I used a bigger loop because in some cases the efficiency tend to decrease on the long run.

I am on a Macosx Snow Leopard 10.6.1, running Apache, Webgrind, and PHP 5.3.1

Could that affect?

Memory allocation/deallocation might be slower on OSX, that would slow down the object creation/destruction… just a guess, I really have no idea.

Are you using a bytecode cache? … I don’t see how that would really affect the result either, since that only affects parsing of the script, as far as I know.