ClearSilver の Perl バインディングを使う(Perlのテンプレートエンジンのベンチマーク)


ClearSilverネタが続いてるわけだけど、今度はPerlバインディングを使ってみた。


ClearSilverをインストールすると同時にPerlバインディングもインストールされるんだけど、PODには何にも書いてない・・

ここAPIがのってるだけ。


というわけでサンプルは以下。

#!/usr/local/bin/perl
use strict;
use warnings;

use ClearSilver;

my $hdf = ClearSilver::HDF->new;
$hdf->setValue('message', 'hello world!');
my $cs = ClearSilver::CS->new($hdf);
$cs->parseFile('hello.cs');
print $cs->render;

気になった点は

  • TTになれてるので、メソッド呼び出しができないのが一番不便(当たり前だけど)
  • HashやListをそのまま渡せないのが不便
my $hash = { Foo => 'Foo', Bar => 'Bar' };
$hdf->setValue('Hash', $hash);

ってやると

Hash {
  Foo = Foo
  Bar = Bar
}

ってなってほしい。

結局こんな感じのラッパーを使うしかないかな。

sub hdf_setValue {
    my ($hdf, $key, $val) = @_;
    if (ref $val eq 'ARRAY') {
        my $index = 0;
        for my $v (@$val) {
            hdf_setValue($hdf, "$key.$index", $v);
            $index++;
        }
    } elsif (ref $val eq 'HASH') {
        while (my ($k, $v) = each %$val) {
            hdf_setValue($hdf, "$key.$k", $v);
        }
    } elsif (ref $val eq 'SCALAR') {
        hdf_setValue($hdf, $key, $$val);
    } elsif (ref $val eq '') {
        $hdf->setValue($key, $val);
    }
}

っていうわけで、Perlで使うのは結構不便。


ただし、めちゃくちゃ速い。
Template-Toolkit、ClearSilver、HTML::Templateでベンチ取ってみた。

benchmark.pl

#!/usr/local/bin/perl
use strict;
use warnings;

use Benchmark qw(timethese cmpthese);
use Template;
use ClearSilver;
use HTML::Template;

my $bench = timethese(10000,
    {
        'Template-Toolkit' => sub {
            my $tt = Template->new;
            my $out;
            $tt->process('hello.tmpl', { message => 'hello world!' }, \$out);
        },
        'ClearSilver' => sub {
            my $hdf = ClearSilver::HDF->new;
            $hdf->setValue('message', 'hello world!');
            my $cs = ClearSilver::CS->new($hdf);
            $cs->parseFile('hello.tmpl');
            my $out = $cs->render;
        },
        'HTML::Template' => sub {
            my $template = HTML::Template->new(filename => 'hello.tmpl');
            $template->param(message => 'hello world!');
            my $out = $template->output;
        },
    },
);
cmpthese($bench);

hello.tmpl

[% message %]
<?cs var:message ?>
<TMPL_VAR NAME=message>

これがこうなる。

Rate Template-Toolkit HTML::Template ClearSilver
Template-Toolkit 592/s -- -82% -97%
HTML::Template 3247/s 448% -- -86%
ClearSilver 23256/s 3828% 616% --


なんだそれ・・・速すぎ。

複雑なテンプレートは試してないけど。


とにかくClearSilverには注目。