XML::LibXML を使って、XML の属性を取り出すときに findvalue メソッドで XPath を使うのと XML::LibXML::Element のメソッド getAttribute を使うのとどちらが早いのかベンチマークしてみました。
Benchmark: timing 10000 iterations of accessor, xpath... accessor: 0 wallclock secs ( 0.05 usr + 0.00 sys = 0.05 CPU) @ 200000.00/s (n=10000) (warning: too few iterations for a reliable count) xpath: 1 wallclock secs ( 0.55 usr + 0.00 sys = 0.55 CPU) @ 18181.82/s (n=10000)
XPath の方が遅いのか。。。XPathエンジンとか重たいのかな?
以下がコードです。
#!/usr/local/bin/perl
use strict;
use warnings;
use XML::LibXML;
use Perl6::Say;
use Benchmark;
my $xp = XML::LibXML->new;
my $doc = $xp->parse_string(<<"XML");
<?xml version="1.0"?>
<doc attr="please">
please ignore.this is a test.
</doc>
XML
my $xml = $doc->documentElement;
timethese (10000, {
'accessor' => sub { $xml->getAttribute('attr') },
'xpath' => sub { $xml->findvalue('@attr') },
});
追記
さらに、Devel::Profile を用いて、上記の timethese の中の accessor と xpath のそれぞれ片方だけを実行した結果の上位10位です。(上記のコードを baz.pl として保存して、perl -d:Profile baz.pl と実行)
'accessor'のみ実行(#'xpath'の行をコメントアウト)
time elapsed (wall): 0.7500
time running program: 0.5730 (76.40%)
time profiling (est.): 0.1770 (23.60%)
number of calls: 41183%Time Sec. #calls sec/call F name
34.91 0.2000 20000 0.000010 :.../Perl/5.8.6/Benchmark.pm:651
18.27 0.1047 10000 0.000010 XML::LibXML::Element::getAttribute
10.43 0.0598 1 0.059758 :.../Perl/5.8.6/Benchmark.pm:675
10.41 0.0597 10000 0.000006 XML::LibXML::Element::_getAttribute
10.30 0.0590 1 0.059044 :.../Perl/5.8.6/Benchmark.pm:682
3.16 0.0181 1 0.018114 :baz.pl:6
1.23 0.0071 383 0.000018 Benchmark::new
1.17 0.0067 0 0.006728 *
1.15 0.0066 1 0.006588 :baz.pl:9
1.10 0.0063 1 0.006291 :baz.pl:8
'xpath'のみ実行(#'accessor'の行をコメントアウト)
time elapsed (wall): 2.2250
time running program: 1.7546 (78.86%)
time profiling (est.): 0.4705 (21.14%)
number of calls: 111103%Time Sec. #calls sec/call F name
21.90 0.3842 10000 0.000038 XML::LibXML::Node::_find
17.64 0.3096 10000 0.000031 XML::LibXML::Node::findvalue
11.83 0.2076 10000 0.000021 XML::LibXML::NodeList::to_literal
11.63 0.2041 20000 0.000010 :.../Perl/5.8.6/Benchmark.pm:651
11.26 0.1976 10000 0.000020 XML::LibXML::Node::find
3.90 0.0684 10000 0.000007 XML::LibXML::Node::string_value
3.56 0.0625 1 0.062548 :.../Perl/5.8.6/Benchmark.pm:682
3.44 0.0604 1 0.060442 :.../Perl/5.8.6/Benchmark.pm:675
3.36 0.0590 10000 0.000006 XML::LibXML::Literal::new
3.23 0.0566 10000 0.000006 XML::LibXML::NodeList::new
Comments