iterate xpath command-or-block
Iterate works very much like a foreach loop with the
same xpath expression, except that it
evaluates the command-or-block as soon as a new node
matching a given xpath is found. As a
limitation, an xpath expression
used with iterate
may consist of one XPath
step only, i.e. it may not contain an XPath step separator
/
.
A possible benefit of using iterate
instead of
foreach is some efficiency when
iterating over huge node-sets. Since
iterate
doesn't compute
the resulting node-set in advance, it
doesn't have to 1) allocate extra memory for it
and 2) (more importantly) doesn't have to sort
the node-list in the document order (which
tends to be slow on large node-sets, unless
index is used). On the other
hand, iterate
suffers from a considerable
speed penalty since it isn't implemented in C (unlike
libxml2's XPath engine).
Author's experience shows that, unless index
is used, iterate
beats
foreach in speed on large
node-lists (>=1500 nodes, but your milage may vary) while
foreach wins on smaller node-lists.
The following two examples give equivalent results.
However, the one using iterate
may be faster if the number of nodes being counted
is huge and document order isn't indexed.
Example 36. Count inhabitants of the kingdom of Rohan in productive age
cd rohan/inhabitants;
iterate child::*[@age>=18 and @age<60] { perl $productive++ };
echo "$productive inhabitants in productive age";
Example 37. Using XPath
$productive=count(rohan/inhabitants/*[@age>=18 and @age<60]);
echo "$productive inhabitants in productive age";
Hint: use e.g. | time cut
pipe-line
redirection to benchmark a XSH2 command on a UNIX system.