PHP Template Engine Comparison. Part 2 (versus Plain PHP)


In my last post I created a small (and very personal) test of different templating engines in PHP (Smarty, Haanga and Twiw). Someone posted a comment asking for the comparison between those template engines and old school phtml. OK I’ve done some tests. It’s a bit difficult to create the template inheritance (without cloning one of the template engines and creating a new one) so I have one approximation with a simple include. It’s not the same but it’s similar. I’ve also implemented cycle filter (OK I’ve borrowed getCycle function from Twig. Not really implemented 😉 )

Using plain PHP files as template is a big temptation. They’re easy to implement and fast. But you need to take care of security issues. For example if you work together with designers, using a template engine is a good solution. It sandboxes our templates and separates the business logic from the HTML. With plain PHP files is very easy to put business logic within templates.

Here we are my examples:

<?php  /* PHP plain. indexFull.phtml */?>
<html>
    <head>
        <title><?= $title ?></title>
    </head>
    <body>
        <h2>An example with <?= ucwords(strtolower($title)) ?></h2>
        <b>Table with <?= $number ?> rows</b>
        <table>
            <?php foreach ($table as $row) { ?>
            <tr bgcolor="<?= cycle(array('#aaaaaa', '#ffffff'), $row['id']) ?>">
                <td><?= $row['id'] ?></td>
                <td><?= $row['name'] ?></td>
            </tr>
            <?php } ?>
        </table>
    </body>
</html>

and the PHP:

$time = microtime(TRUE);
$mem = memory_get_usage();

define('BASE_DIR', dirname(__file__));

class DirtyTemplateEngine
{
    protected $_templateDir = null;
    public function __construct($path)
    {
        $this->_templateDir = $path;
    }

    function display($template,array $vars) {
        extract($vars);
        ob_start();

        function cycle($values, $i)
        {
            if (!is_array($values) && !$values instanceof ArrayAccess) {
                return $values;
            }

            return $values[$i % count($values)];
        }
        include($this->_templateDir . '/' . $template);
        echo ob_get_clean();
    }
}

$tpl = new DirtyTemplateEngine(BASE_DIR . "/php/templates");

$rows = 50;
$data = array();
for ($i = 0; $i < $rows; $i++) {
    $data[] = array('id' => $i, 'name' => "name {$i}");
}

$tpl->display('indexFull.phtml', array(
    'number' => $rows,
    'title'  => 'php',
    'table'  => $data
));

print_r(array('memory' => (memory_get_usage() - $mem) / (1024 * 1024), 'seconds' => microtime(TRUE) - $time));

And with template “inheritance”
I know that maybe this test is not comparable with “real” template inheritance

<?php  /* PHP plain. index.phtml */?>
<html>
    <head>
        <title><?= $title ?></title>
    </head>
    <body>
        <h2>An example with <?= ucwords(strtolower($title)) ?></h2>
        <b>Table with <?= $number ?> rows</b>
        <?php include 'block.phtml' ?>;
    </body>
</html>
<?php  /* PHP plain. block.phtml */?>
<table>
    <?php foreach ($table as $row) { ?>
    <tr bgcolor="<?= cycle(array('#aaaaaa', '#ffffff'), $row['id']) ?>">
        <td><?= $row['id'] ?></td>
        <td><?= $row['name'] ?></td>
    </tr>
    <?php } ?>
</table>
(50 rows) Smarty Twig Haanga PHP
Simple template Memory: 0.684497
Time: 0.023710
Memory: 0.598434
Time: 0.025444
Memory: 0.124019
Time: 0.004004
Mem: 0.026512
Time: 0.001536
Template Inheritance Memory: 0.685134
Time: 0.023761
Memory: 0.619461
Time: 0.028100
Memory: 0.133472
Time: 0.005005
Mem: 0.026512
Time: 0.001536
(1000 rows) Smarty Twig Haanga PHP
Simple template Memory: 1.222743
Time: 0.094762
Memory: 1.033226
Time: 0.196187
Memory: 0.558811
Time: 0.043151
Mem: 0.576526
Time: 0.028120
Template Inheritance Memory: 1.194095
Time: 0.090528
Memory: 1.054237
Time: 0.191694
Memory: 0.646381
Time: 0.044402
Mem: 0.537937
Time: 0.043996

Haanga really rocks again. The performance is very similar than plain PHP templating. Plain PHP is obviously the fastest but Haanga is almost the same. It’s a pity the lack of complete documentation (it’s very hard look into the source code to find features and examples). As Cesar Rodas (Haanga’s developer) told us in a comment Haanga generates self-contained PHP code. Because of that the performance is close to plain PHP execution.

Another useful links about it here and here.

15 thoughts on “PHP Template Engine Comparison. Part 2 (versus Plain PHP)

  1. This is realy impresive for hanga to be almost as fast as plain phtml. Now I will have reconsider using php templates for my views.

  2. I used to be an advocate of templating systems, as they were seen as “good practise” in the PHP community. But I soon learnt that unless you have a specific requirement that cannot be met by PHP, don’t bother with them, they only increase the execution overheads and learning required.

  3. And where is the difference with Your first post ? You only add next engine.
    Show result with cache and without , using objects and static methods, loops, specific function and configure, compare out of the box. What functions You have when you download script, default configuration and what you can configure.
    Or change title to speed test. 🙂

    1. As I said in the first post it’s my personal template engine comparison. I normally use only a few things of template engines (not all of them) and I wanted to test those functionality. As I said it’s not a exhaustive test. But I like to share it.

      The second post is due to a comment in the first post wondering about the comarison between templating engines and plain PHP code. Because of that I have done the same test with plain PHP templates.

  4. Isn’t the generation of self-contained source code nearly the same as caching? Thought that all template engines do exactly that as a caching mechanism..

    1. Not really. As far as I understand cache is the saved HTML output of the templates. Self contained PHP code means it doesn’t depend on extra files. But I will check it.

  5. Hi,

    I was almost ready to go with rain TPL , since they had posted some great speeds.

    http://www.raintpl.com/PHP-Template-Engines-Speed-Test/

    Now I’m wondering how it would compare with Haanga?

    I’m still researching options, but just on a simple look in the directories, Haanga seems to be a full system compared to rainTPL but I could be wrong.

    Would you add rain to your testing?

  6. Nice article, thanks.
    Actually, I’ve checked the self-contained php code compiled by Haanga. (Look into Haanga’s compiled php code is quite simple, just less the file in the cache folder)

    In the php code, there is only simply a function to render the page by using the varaibles as arguments. ( Except the situation, if the template need to include or extend other template, in this situation, the function will call Haanga::load() again.)

    It is just like a php function written by a robot to echo page according to the arguments.

    So I’m a little of confused why there is difference between Haanga & Plain PHP in simple template test. Do you think it is because Haanga’s loop code or other reason?

    Thank you again for your sharing..^_^

    1. As the author said in one of the comments, there is a small piece of haanga that compares if the template needs to be compiled or not and includes it. Here is the slight different between the simple PHP file and the Haanga one. As he said we can take the compiled files and execute them without the full library. Cool, isn’t it?

      1. Yes…It is really cool, so I am very interested in Haanga now, not only its speed & memory usage, but also it is using django syntax which is easy to learn and not only supported by Haanga.

        Hi.. I’ve done the test also (since it’s chinese lunar year day in Taiwan) by using your example code, and I’ve found the main difference between your phtml code and the code generated by Haanga. That’s — htmlspecialchars(). Haanga almost auto escape every variable using in html. Maybe you should disable auto-escape or either add auto-escape onto your phtml. Just for your information. Thanks again for the sharing…^_^

      2. cool. AFAIK haanga autoescape all with htmlspecialchars. this fact plus the logic for comparing if the template must be compiled or not may be the difference between plain PHP and haanga.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.