XML technologies / XML / Perl & XML / Working with trees: XPath, XSLT and more / Optimized tree processing

(Excerpt from “Perl & XML” by Erik T. Ray & Jason McIntosh)

The main drawback of working with trees is their enormous consumption of memory and processing time. This matters less for small documents, but changes as documents grow to thousands of nodes. A typical book of a few hundred pages can easily contain tens of thousands of nodes. Each node is represented by an object whose creation takes memory and time.

But perhaps you do not need the entire tree? Often a small subtree suffices, while still benefiting from convenient processing. In that case, you may find XML::Twig useful. (We introduced the module in XPath .) The module lets you specify subtrees (the “twigs”) required for further processing. The result is an interesting mixture of tree-based and event-driven processing, balancing speed and memory on the one hand with convenience on the other.

XML::Twig has three operating modes: the regular, classic tree mode already familiar to us; “chunk” mode, which also builds a complete tree but keeps only part of it in memory; and a multiple-root mode that keeps only selected twigs in memory.

The following example uses the “chunk” mode of XML::Twig. Its input is a book written in DocBook with several <chapter> elements. Such documents can be enormous: a hundred megabytes or more is not unusual. The program handles chapters individually, reducing memory requirements to those of the largest chapter.

Example: A program using chunks

use XML::Twig;   

# Initialisierung und Aufruf des Parsers, Ausgabe des bearbeiteten "Twig"
my $twig = new XML::Twig( TwigHandlers => { "chapter" => \&process_chapter });
$twig->parsefile( shift @ARGV );
$twig->print;

# Handler für Kapitel: Verarbeitung und Ausgabe
sub process_chapter {
   my( $tree, $elem ) = @_;
   &process_element( $elem );
   $tree->flush_up_to( $elem ); # Kommentieren Sie diese Zeile einmal zur Probe aus
   # und beobachten Sie, wie der Speicherverbrauch wächst.
}

# Ein 'foo' wird an den Elementnamen angehängt
sub process_element {
   my $elem = shift;
   $elem->set_gi( $elem->gi . 'foo' );
   my @children = $elem->children;
   foreach my $child ( @children ) {
      next if( $child->gi eq '#PCDATA' );
      &process_element( $child );
   }
}

The program’s “processing” consists of appending “foo” to every element name. Its only purpose is to make the program run a little longer, giving us time to check memory consumption. Note the following line in the function process_chapter( ):

 $tree->flush_up_to( $elem ); 

This command is what actually saves memory. Without it, the whole tree would eventually be built. The call outputs and discards the subtree accumulated so far. This operation is called a flush. Memory consumption therefore corresponds to the chapter currently being read.

So much for theory. To test it in practice, we ran the program on a 3 MB file, first without this line and then with it. Without flushing, the program required no less than 30 MB. The ratio of gross to net data is alarming: a factor of ten was not immediately to be expected. With flushing enabled, only a few megabytes were needed, about 90% less. Both cases ultimately traverse the entire tree, so processing time was identical. Time can sometimes also be saved by using multiple roots.

Multiple roots are obtained by specifying the XPath expressions for the twigs to build. If the twigs are considerably smaller than the whole document, you save a corresponding amount of memory and processing time. Our chunk-mode example could only reduce memory consumption because all the <chapter> elements together make up the entire document. Let us therefore consider a more suitable example.

The program below again reads a DocBook document and outputs chapter titles—a minimal table of contents. Clearly, this information does not require reading each whole chapter; only the <title> elements matter. We therefore specify the titles as roots using the XPath expression chapter/title.

Example: A program with many twigs

use XML::Twig;

my $twig = new XML::Twig( TwigRoots => { 'chapter/title' => \&output_title });
$twig->parsefile( shift @ARGV );

sub output_title {
   my( $tree, $elem ) = @_;
   print $elem->text, "\n";
}

The crucial point here is the line with the keyword TwigRoots. Its value is a hash reference containing pairs of XPath expressions and handlers. The program builds only subtrees matching the specified XPath expressions. Here, that is only a fraction of the whole document, so we can expect minimal memory and time consumption.

How much do we gain? With the same test data, our program used about 2 MB of memory and took 13 seconds, compared with the original 30 MB and a full minute. Resource consumption is therefore significantly lower.

XML::Twig can enormously improve the performance of tree-based programs, but requires a precise understanding of the modes and their advantages and disadvantages. If the twigs or chunks are large, you will save nothing overall.

  

  

 

 

 

back to top