FunctionalPerl

 view release on metacpan or  search on metacpan

lib/PXML/Preserialize.pm  view on Meta::CPAN

#
# Copyright (c) 2015-2020 Christian Jaeger, copying@christianjaeger.ch
#
# This is free software, offered under either the same terms as perl 5
# or the terms of the Artistic License version 2 or the terms of the
# MIT License (Expat version). See the file COPYING.md that came
# bundled with this file.
#

=head1 NAME

PXML::Preserialize - faster PXML templating through preserialization

=head1 SYNOPSIS

    use PXML::Preserialize qw(pxmlfunc pxmlpre);
    use PXML::XHTML qw(A B);

    my $link_normal = sub {
        my ($href,$body)=@_;
        A {href=> $href}, $body
    };

    my $link_fast = pxmlfunc {
        my ($href,$body)=@_; # can take up to 10[?] arguments.
        A {href=> $href}, $body
    };

    # the `2` is the number of arguments
    my $link_fast2 = pxmlpre 2, $link_normal;

    # these expressions are all returning the same result, but the second
    # and third are (supposedly) evaluated faster than the first:
    is $link_normal->("http://foo", [B("Foo"), "Bar"])->string,
       '<a href="http://foo"><b>Foo</b>Bar</a>';
    is $link_fast->("http://foo", [B("Foo"), "Bar"])->string,
       '<a href="http://foo"><b>Foo</b>Bar</a>';
    is $link_fast2->("http://foo", [B("Foo"), "Bar"])->string,
       '<a href="http://foo"><b>Foo</b>Bar</a>';


=head1 DESCRIPTION

=for test ignore

PXML represents every XML/HTML element as an individual Perl object,
and both building up a PXML tree and serializing it is somewhat
costly.

And even if only a few strings change in a (sub)tree, a new tree
instance needs to be created and serialized for every set of those
strings.

This overhead can be eliminated by pre-serializing the segments of the
tree that don't change.

This module offers C<pxmlpre>, a function that takes a user supplied
function which maps some number of arguments to a PXML tree with those
arguments inserted, and returns a function that maps those same
arguments to an array with preserialized fragments and the (escaped)
argument values so that the PXML serialization functions don't have
any work to do except for printing the fragments and values.

With the example from the synopsis:

 &$link_normal("foo","bar")

returns a PXML element with name "a", a hash C<{href=> "foo"}> as
attributes, and "bar" as the body. C<<->string>> walks over the element
and hash and body and turns all parts into the proper XML syntax.

 &$link_fast2("foo","bar")

returns

 bless [ $fragment1, "foo", $fragment2, "$bar", $fragment3 ], "PXML::Body"



( run in 0.467 second using v1.01-cache-2.11-cpan-354807fb38d )