Debian Codegraph @

doc/performance.txt

raw
1 ====================
2 Benchmarks and Speed
3 ====================
4
5 :Author:
6 Stefan Behnel
7
8 .. meta::
9 :description: Performance evaluation of lxml and ElementTree:
10 fast operations, common pitfalls and optimisation hints.
11 :keywords: Python XML parser performance, XML processing, performance comparison,
12 lxml performance, lxml.etree, lxml.objectify, benchmarks, ElementTree
13
14
15 lxml.etree is a very fast XML library. Most of this is due to the
16 speed of libxml2, e.g. the parser and serialiser, or the XPath engine.
17 Other areas of lxml were specifically written for high performance in
18 high-level operations, such as the tree iterators.
19
20 On the other hand, the simplicity of lxml sometimes hides internal
21 operations that are more costly than the API suggests. If you are not
22 aware of these cases, lxml may not always perform as you expect. A
23 common example in the Python world is the Python list type. New users
24 often expect it to be a linked list, while it actually is implemented
25 as an array, which results in a completely different complexity for
26 common operations.
27
28 Similarly, the tree model of libxml2 is more complex than what lxml's
29 ElementTree API projects into Python space, so some operations may
30 show unexpected performance. Rest assured that most lxml users will
31 not notice this in real life, as lxml is very fast in absolute
32 numbers. It is definitely fast enough for most applications, so lxml
33 is probably somewhere between 'fast enough' and 'the best choice' for
34 yours. Read some messages_ from happy_ users_ to see what we mean.
35
36 .. _messages: http://permalink.gmane.org/gmane.comp.python.lxml.devel/3250
37 .. _happy: http://article.gmane.org/gmane.comp.python.lxml.devel/3246
38 .. _users: http://thread.gmane.org/gmane.comp.python.lxml.devel/3244/focus=3244
39
40 This text describes where lxml.etree (abbreviated to 'lxe') excels, gives
41 hints on some performance traps and compares the overall performance to the
42 original ElementTree_ (ET) and cElementTree_ (cET) libraries by Fredrik Lundh.
43 The cElementTree library is a fast C-implementation of the original
44 ElementTree.
45
46 .. _ElementTree: http://effbot.org/zone/element-index.htm
47 .. _cElementTree: http://effbot.org/zone/celementtree.htm
48
49 .. contents::
50 ..
51 1 How to read the timings
52 2 Bad things first
53 3 Parsing and Serialising
54 4 The ElementTree API
55 5 Tree traversal
56 6 XPath
57 7 lxml.objectify
58
59
60 General notes
61 =============
62
63 First thing to say: there *is* an overhead involved in having a DOM-like C
64 library mimic the ElementTree API. As opposed to ElementTree, lxml has to
65 generate Python representations of tree nodes on the fly when asked for them,
66 and the internal tree structure of libxml2 results in a higher maintenance
67 overhead than the simpler top-down structure of ElementTree. What this means
68 is: the more of your code runs in Python, the less you can benefit from the
69 speed of lxml and libxml2. Note, however, that this is true for most
70 performance critical Python applications. No one would implement Fourier
71 transformations in pure Python when you can use NumPy.
72
73 The up side then is that lxml provides powerful tools like tree iterators,
74 XPath and XSLT, that can handle complex operations at the speed of C. Their
75 pythonic API in lxml makes them so flexible that most applications can easily
76 benefit from them.
77
78
79 How to read the timings
80 =======================
81
82 The statements made here are backed by the (micro-)benchmark scripts
83 `bench_etree.py`_, `bench_xpath.py`_ and `bench_objectify.py`_ that come with
84 the lxml source distribution. They are distributed under the same BSD license
85 as lxml itself, and the lxml project would like to promote them as a general
86 benchmarking suite for all ElementTree implementations. New benchmarks are
87 very easy to add as tiny test methods, so if you write a performance test for
88 a specific part of the API yourself, please consider sending it to the lxml
89 mailing list.
90
91 The timings presented below compare lxml 4.6.3 (with libxml2 2.9.10) to the
92 latest released versions of ElementTree (with cElementTree as accelerator
93 module) in the standard library of CPython 3.8.10. They were run
94 single-threaded on a 2.3GHz 64bit double core Intel i5 machine under
95 Ubuntu Linux 20.04 (Focal).
96
97 .. _`bench_etree.py`: https://github.com/lxml/lxml/blob/master/benchmark/bench_etree.py
98 .. _`bench_xpath.py`: https://github.com/lxml/lxml/blob/master/benchmark/bench_xpath.py
99 .. _`bench_objectify.py`: https://github.com/lxml/lxml/blob/master/benchmark/bench_objectify.py
100
101 The scripts run a number of simple tests on the different libraries, using
102 different XML tree configurations: different tree sizes (T1-4), with or
103 without attributes (-/A), with or without ASCII string or unicode text
104 (-/S/U), and either against a tree or its serialised XML form (T/X). In the
105 result extracts cited below, T1 refers to a 3-level tree with many children at
106 the third level, T2 is swapped around to have many children below the root
107 element, T3 is a deep tree with few children at each level and T4 is a small
108 tree, slightly broader than deep. If repetition is involved, this usually
109 means running the benchmark in a loop over all children of the tree root,
110 otherwise, the operation is run on the root node (C/R).
111
112 As an example, the character code ``(SATR T1)`` states that the benchmark was
113 running for tree T1, with plain string text (S) and attributes (A). It was
114 run against the root element (R) in the tree structure of the data (T).
115
116 Note that very small operations are repeated in integer loops to make them
117 measurable. It is therefore not always possible to compare the absolute
118 timings of, say, a single access benchmark (which usually loops) and a 'get
119 all in one step' benchmark, which already takes enough time to be measurable
120 and is therefore measured as is. An example is the index access to a single
121 child, which cannot be compared to the timings for ``getchildren()``. Take a
122 look at the concrete benchmarks in the scripts to understand how the numbers
123 compare.
124
125
126 Parsing and Serialising
127 =======================
128
129 Serialisation is an area where lxml excels. The reason is that it
130 executes entirely at the C level, without any interaction with Python
131 code. The results are rather impressive, especially for UTF-8, which
132 is native to libxml2. While 20 to 40 times faster than (c)ElementTree
133 1.2 (which was part of the standard library before Python 2.7/3.2),
134 lxml is still several times faster than the much improved
135 ElementTree 1.3 in recent Python versions::
136
137 lxe: tostring_utf16 (S-TR T1) 5.9340 msec/pass
138 cET: tostring_utf16 (S-TR T1) 38.3270 msec/pass
139
140 lxe: tostring_utf16 (UATR T1) 6.2032 msec/pass
141 cET: tostring_utf16 (UATR T1) 37.7944 msec/pass
142
143 lxe: tostring_utf16 (S-TR T2) 6.1841 msec/pass
144 cET: tostring_utf16 (S-TR T2) 40.2577 msec/pass
145
146 lxe: tostring_utf8 (S-TR T2) 4.6697 msec/pass
147 cET: tostring_utf8 (S-TR T2) 30.5173 msec/pass
148
149 lxe: tostring_utf8 (U-TR T3) 1.2085 msec/pass
150 cET: tostring_utf8 (U-TR T3) 9.0246 msec/pass
151
152 The difference is somewhat smaller for plain text serialisation::
153
154 lxe: tostring_text_ascii (S-TR T1) 2.6727 msec/pass
155 cET: tostring_text_ascii (S-TR T1) 2.9683 msec/pass
156
157 lxe: tostring_text_ascii (S-TR T3) 0.6952 msec/pass
158 cET: tostring_text_ascii (S-TR T3) 1.0073 msec/pass
159
160 lxe: tostring_text_utf16 (S-TR T1) 2.7366 msec/pass
161 cET: tostring_text_utf16 (S-TR T1) 7.3647 msec/pass
162
163 lxe: tostring_text_utf16 (U-TR T1) 3.0322 msec/pass
164 cET: tostring_text_utf16 (U-TR T1) 7.5922 msec/pass
165
166 The ``tostring()`` function also supports serialisation to a Python
167 unicode string object, which is currently faster in ElementTree
168 under CPython 3.8::
169
170 lxe: tostring_text_unicode (S-TR T1) 2.7645 msec/pass
171 cET: tostring_text_unicode (S-TR T1) 1.1806 msec/pass
172
173 lxe: tostring_text_unicode (U-TR T1) 2.9871 msec/pass
174 cET: tostring_text_unicode (U-TR T1) 1.1659 msec/pass
175
176 lxe: tostring_text_unicode (S-TR T3) 0.7446 msec/pass
177 cET: tostring_text_unicode (S-TR T3) 0.4532 msec/pass
178
179 lxe: tostring_text_unicode (U-TR T4) 0.0048 msec/pass
180 cET: tostring_text_unicode (U-TR T4) 0.0134 msec/pass
181
182 For parsing, lxml.etree and cElementTree compete for the medal.
183 Depending on the input, either of the two can be faster. The (c)ET
184 libraries use a very thin layer on top of the expat parser, which is
185 known to be very fast. Here are some timings from the benchmarking
186 suite::
187
188 lxe: parse_bytesIO (SAXR T1) 14.2074 msec/pass
189 cET: parse_bytesIO (SAXR T1) 7.9336 msec/pass
190
191 lxe: parse_bytesIO (S-XR T3) 1.4477 msec/pass
192 cET: parse_bytesIO (S-XR T3) 2.1925 msec/pass
193
194 lxe: parse_bytesIO (UAXR T3) 8.4128 msec/pass
195 cET: parse_bytesIO (UAXR T3) 12.2926 msec/pass
196
197 And another couple of timings `from a benchmark`_ that Fredrik Lundh
198 `used to promote cElementTree`_, comparing a number of different
199 parsers. First, parsing a 274KB XML file containing Shakespeare's
200 Hamlet::
201
202 xml.etree.ElementTree.parse done in 0.006 seconds
203 xml.etree.cElementTree.parse done in 0.007 seconds
204 xml.etree.cElementTree.XMLParser.feed(): 6636 nodes read in 0.006 seconds
205 lxml.etree.parse done in 0.004 seconds
206 drop_whitespace.parse done in 0.004 seconds
207 lxml.etree.XMLParser.feed(): 6636 nodes read in 0.004 seconds
208 minidom tree read in 0.066 seconds
209
210 And a 3.4MB XML file containing the Old Testament::
211
212 xml.etree.ElementTree.parse done in 0.037 seconds
213 xml.etree.cElementTree.parse done in 0.036 seconds
214 xml.etree.cElementTree.XMLParser.feed(): 25317 nodes read in 0.036 seconds
215 lxml.etree.parse done in 0.025 seconds
216 drop_whitespace.parse done in 0.022 seconds
217 lxml.etree.XMLParser.feed(): 25317 nodes read in 0.026 seconds
218 minidom tree read in 0.194 seconds
219
220 .. _`from a benchmark`: http://svn.effbot.org/public/elementtree-1.3/benchmark.py
221 .. _`used to promote cElementTree`: http://effbot.org/zone/celementtree.htm#benchmarks
222
223 Here are the same benchmarks again, but including the memory usage
224 of the process in KB before and after parsing (using os.fork() to
225 make sure we start from a clean state each time). For the 274KB
226 hamlet.xml file::
227
228 Memory usage: 9256
229 xml.etree.ElementTree.parse done in 0.006 seconds
230 Memory usage: 12764 (+3508)
231 xml.etree.cElementTree.parse done in 0.007 seconds
232 Memory usage: 12764 (+3508)
233 xml.etree.cElementTree.XMLParser.feed(): 6636 nodes read in 0.006 seconds
234 Memory usage: 12720 (+3464)
235 lxml.etree.parse done in 0.004 seconds
236 Memory usage: 15052 (+5796)
237 drop_whitespace.parse done in 0.004 seconds
238 Memory usage: 14040 (+4784)
239 lxml.etree.XMLParser.feed(): 6636 nodes read in 0.004 seconds
240 Memory usage: 15812 (+6556)
241 minidom tree read in 0.066 seconds
242 Memory usage: 15332 (+6076)
243
244 And for the 3.4MB Old Testament XML file::
245
246 Memory usage: 12456
247 xml.etree.ElementTree.parse done in 0.037 seconds
248 Memory usage: 23288 (+10832)
249 xml.etree.cElementTree.parse done in 0.036 seconds
250 Memory usage: 23288 (+10832)
251 xml.etree.cElementTree.XMLParser.feed(): 25317 nodes read in 0.036 seconds
252 Memory usage: 23644 (+11220)
253 lxml.etree.parse done in 0.025 seconds
254 Memory usage: 31404 (+18948)
255 drop_whitespace.parse done in 0.022 seconds
256 Memory usage: 28752 (+16296)
257 lxml.etree.XMLParser.feed(): 25317 nodes read in 0.026 seconds
258 Memory usage: 33924 (+21500)
259 minidom tree read in 0.194 seconds
260 Memory usage: 31284 (+18828)
261
262 As can be seen from the sizes, both lxml.etree and cElementTree are
263 rather memory friendly and fast. Comparing to older CPython
264 versions, the memory footprint of the minidom library was considerably
265 reduced in CPython 3.3, by about a factor of 4 in this case.
266
267 For plain parser performance, lxml.etree and cElementTree tend to stay
268 rather close to each other, usually within a factor of two, with
269 winners well distributed over both sides. Similar timings can be
270 observed for the ``iterparse()`` function::
271
272 lxe: iterparse_bytesIO (SAXR T1) 20.3598 msec/pass
273 cET: iterparse_bytesIO (SAXR T1) 10.8948 msec/pass
274
275 lxe: iterparse_bytesIO (UAXR T3) 10.1640 msec/pass
276 cET: iterparse_bytesIO (UAXR T3) 12.9926 msec/pass
277
278 However, if you benchmark the complete round-trip of a serialise-parse
279 cycle, the numbers will look similar to these::
280
281 lxe: write_utf8_parse_bytesIO (S-TR T1) 18.9857 msec/pass
282 cET: write_utf8_parse_bytesIO (S-TR T1) 35.7475 msec/pass
283
284 lxe: write_utf8_parse_bytesIO (UATR T2) 22.4853 msec/pass
285 cET: write_utf8_parse_bytesIO (UATR T2) 42.6254 msec/pass
286
287 lxe: write_utf8_parse_bytesIO (S-TR T3) 3.3801 msec/pass
288 cET: write_utf8_parse_bytesIO (S-TR T3) 11.2493 msec/pass
289
290 lxe: write_utf8_parse_bytesIO (SATR T4) 0.4263 msec/pass
291 cET: write_utf8_parse_bytesIO (SATR T4) 1.0326 msec/pass
292
293 For applications that require a high parser throughput of large files,
294 and that do little to no serialization, both cET and lxml.etree are a
295 good choice. The cET library is particularly fast for iterparse
296 applications that extract small amounts of data or aggregate
297 information from large XML data sets that do not fit into memory. If
298 it comes to round-trip performance, however, lxml is multiple times
299 faster in total. So, whenever the input documents are not
300 considerably larger than the output, lxml is the clear winner.
301
302 Regarding HTML parsing, Ian Bicking has done some `benchmarking on
303 lxml's HTML parser`_, comparing it to a number of other famous HTML
304 parser tools for Python. lxml wins this contest by quite a length.
305 To give an idea, the numbers suggest that lxml.html can run a couple
306 of parse-serialise cycles in the time that other tools need for
307 parsing alone. The comparison even shows some very favourable results
308 regarding memory consumption.
309
310 .. _`benchmarking on lxml's HTML parser`: http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/
311
312 Liza Daly has written an article that presents a couple of tweaks to
313 get the most out of lxml's parser for very large XML documents. She
314 quite favourably positions ``lxml.etree`` as a tool for
315 `high-performance XML parsing`_.
316
317 .. _`high-performance XML parsing`: http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
318
319 Finally, `xml.com`_ has a couple of publications about XML parser
320 performance. Farwick and Hafner have written two interesting articles
321 that compare the parser of libxml2 to some major Java based XML
322 parsers. One deals with `event-driven parser performance`_, the other
323 one presents `benchmark results comparing DOM parsers`_. Both
324 comparisons suggest that libxml2's parser performance is largely
325 superior to all commonly used Java parsers in almost all cases. Note
326 that the C parser benchmark results are based on xmlbench_, which uses
327 a simpler setup for libxml2 than lxml does.
328
329 .. _`xml.com`: http://www.xml.com/
330 .. _`event-driven parser performance`: http://www.xml.com/lpt/a/1702
331 .. _`benchmark results comparing DOM parsers`: http://www.xml.com/lpt/a/1703
332 .. _xmlbench: http://xmlbench.sourceforge.net/
333
334
335 The ElementTree API
336 ===================
337
338 Since all three libraries implement the same API, their performance is
339 easy to compare in this area. A major disadvantage for lxml's
340 performance is the different tree model that underlies libxml2. It
341 allows lxml to provide parent pointers for elements and full XPath
342 support, but also increases the overhead of tree building and
343 restructuring. This can be seen from the tree setup times of the
344 benchmark (given in seconds)::
345
346 lxe: -- S- U- -A SA UA
347 T1: 0.0219 0.0254 0.0257 0.0216 0.0259 0.0259
348 T2: 0.0234 0.0279 0.0283 0.0271 0.0318 0.0307
349 T3: 0.0051 0.0050 0.0058 0.0218 0.0233 0.0231
350 T4: 0.0001 0.0001 0.0001 0.0004 0.0004 0.0004
351 cET: -- S- U- -A SA UA
352 T1: 0.0035 0.0029 0.0078 0.0031 0.0031 0.0029
353 T2: 0.0047 0.0051 0.0053 0.0046 0.0055 0.0048
354 T3: 0.0016 0.0216 0.0027 0.0021 0.0023 0.0026
355 T4: 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000
356
357 The timings are somewhat close to each other, although cET can be
358 several times faster than lxml for larger trees. One of the
359 reasons is that lxml must encode incoming string data and tag names
360 into UTF-8, and additionally discard the created Python elements
361 after their use, when they are no longer referenced. ElementTree
362 represents the tree itself through these objects, which reduces
363 the overhead in creating them.
364
365
366 Child access
367 ------------
368
369 The same tree overhead makes operations like collecting children as in
370 ``list(element)`` more costly in lxml. Where cET can quickly create
371 a shallow copy of their list of children, lxml has to create a Python
372 object for each child and collect them in a list::
373
374 lxe: root_list_children (--TR T1) 0.0036 msec/pass
375 cET: root_list_children (--TR T1) 0.0005 msec/pass
376
377 lxe: root_list_children (--TR T2) 0.0634 msec/pass
378 cET: root_list_children (--TR T2) 0.0086 msec/pass
379
380 This handicap is also visible when accessing single children::
381
382 lxe: first_child (--TR T2) 0.0601 msec/pass
383 cET: first_child (--TR T2) 0.0548 msec/pass
384
385 lxe: last_child (--TR T1) 0.0570 msec/pass
386 cET: last_child (--TR T1) 0.0534 msec/pass
387
388 ... unless you also add the time to find a child index in a bigger
389 list. ET and cET use Python lists here, which are based on arrays.
390 The data structure used by libxml2 is a linked tree, and thus, a
391 linked list of children::
392
393 lxe: middle_child (--TR T1) 0.0892 msec/pass
394 cET: middle_child (--TR T1) 0.0510 msec/pass
395
396 lxe: middle_child (--TR T2) 2.3038 msec/pass
397 cET: middle_child (--TR T2) 0.0508 msec/pass
398
399
400 Element creation
401 ----------------
402
403 As opposed to ET, libxml2 has a notion of documents that each element must be
404 in. This results in a major performance difference for creating independent
405 Elements that end up in independently created documents::
406
407 lxe: create_elements (--TC T2) 0.8032 msec/pass
408 cET: create_elements (--TC T2) 0.0675 msec/pass
409
410 Therefore, it is always preferable to create Elements for the document they
411 are supposed to end up in, either as SubElements of an Element or using the
412 explicit ``Element.makeelement()`` call::
413
414 lxe: makeelement (--TC T2) 0.8030 msec/pass
415 cET: makeelement (--TC T2) 0.0625 msec/pass
416
417 lxe: create_subelements (--TC T2) 0.8621 msec/pass
418 cET: create_subelements (--TC T2) 0.0923 msec/pass
419
420 So, if the main performance bottleneck of an application is creating large XML
421 trees in memory through calls to Element and SubElement, cET is the best
422 choice. Note, however, that the serialisation performance may even out this
423 advantage, especially for smaller trees and trees with many attributes.
424
425
426 Merging different sources
427 -------------------------
428
429 A critical action for lxml is moving elements between document contexts. It
430 requires lxml to do recursive adaptations throughout the moved tree structure.
431
432 The following benchmark appends all root children of the second tree to the
433 root of the first tree::
434
435 lxe: append_from_document (--TR T1,T2) 1.3800 msec/pass
436 cET: append_from_document (--TR T1,T2) 0.0513 msec/pass
437
438 lxe: append_from_document (--TR T3,T4) 0.0150 msec/pass
439 cET: append_from_document (--TR T3,T4) 0.0026 msec/pass
440
441 Although these are fairly small numbers compared to parsing, this easily shows
442 the different performance classes for lxml and (c)ET. Where the latter do not
443 have to care about parent pointers and tree structures, lxml has to deep
444 traverse the appended tree. The performance difference therefore increases
445 with the size of the tree that is moved.
446
447 This difference is not always as visible, but applies to most parts of the
448 API, like inserting newly created elements::
449
450 lxe: insert_from_document (--TR T1,T2) 5.2345 msec/pass
451 cET: insert_from_document (--TR T1,T2) 0.0732 msec/pass
452
453 or replacing the child slice by a newly created element::
454
455 lxe: replace_children_element (--TC T1) 0.0720 msec/pass
456 cET: replace_children_element (--TC T1) 0.0105 msec/pass
457
458 as opposed to replacing the slice with an existing element from the
459 same document::
460
461 lxe: replace_children (--TC T1) 0.0060 msec/pass
462 cET: replace_children (--TC T1) 0.0050 msec/pass
463
464 While these numbers are too small to provide a major performance
465 impact in practice, you should keep this difference in mind when you
466 merge very large trees. Note that Elements have a ``makeelement()``
467 method that allows to create an Element within the same document,
468 thus avoiding the merge overhead when inserting it into that tree.
469
470
471 deepcopy
472 --------
473
474 Deep copying a tree is fast in lxml::
475
476 lxe: deepcopy_all (--TR T1) 4.1246 msec/pass
477 cET: deepcopy_all (--TR T1) 2.5451 msec/pass
478
479 lxe: deepcopy_all (-ATR T2) 4.7867 msec/pass
480 cET: deepcopy_all (-ATR T2) 2.7504 msec/pass
481
482 lxe: deepcopy_all (S-TR T3) 1.0097 msec/pass
483 cET: deepcopy_all (S-TR T3) 0.6278 msec/pass
484
485 So, for example, if you have a database-like scenario where you parse in a
486 large tree and then search and copy independent subtrees from it for further
487 processing, lxml is by far the best choice here.
488
489
490 Tree traversal
491 --------------
492
493 Another important area in XML processing is iteration for tree
494 traversal. If your algorithms can benefit from step-by-step
495 traversal of the XML tree and especially if few elements are of
496 interest or the target element tag name is known, the ``.iter()``
497 method is a good choice::
498
499 lxe: iter_all (--TR T1) 1.3661 msec/pass
500 cET: iter_all (--TR T1) 0.2670 msec/pass
501
502 lxe: iter_islice (--TR T2) 0.0122 msec/pass
503 cET: iter_islice (--TR T2) 0.0033 msec/pass
504
505 lxe: iter_tag (--TR T2) 0.0098 msec/pass
506 cET: iter_tag (--TR T2) 0.0086 msec/pass
507
508 lxe: iter_tag_all (--TR T2) 0.6840 msec/pass
509 cET: iter_tag_all (--TR T2) 0.4323 msec/pass
510
511 This translates directly into similar timings for ``Element.findall()``::
512
513 lxe: findall (--TR T2) 3.9611 msec/pass
514 cET: findall (--TR T2) 0.9227 msec/pass
515
516 lxe: findall (--TR T3) 0.3989 msec/pass
517 cET: findall (--TR T3) 0.2670 msec/pass
518
519 lxe: findall_tag (--TR T2) 0.7420 msec/pass
520 cET: findall_tag (--TR T2) 0.4942 msec/pass
521
522 lxe: findall_tag (--TR T3) 0.1099 msec/pass
523 cET: findall_tag (--TR T3) 0.1748 msec/pass
524
525 Note that all three libraries currently use the same Python
526 implementation for ``.findall()``, except for their native tree
527 iterator (``element.iter()``). In general, lxml is very fast
528 for iteration, but loses ground against cET when many Elements
529 are found and need to be instantiated. So, the more selective
530 your search is, the faster lxml will run.
531
532
533 XPath
534 =====
535
536 The following timings are based on the benchmark script `bench_xpath.py`_.
537
538 This part of lxml does not have an equivalent in ElementTree. However, lxml
539 provides more than one way of accessing it and you should take care which part
540 of the lxml API you use. The most straightforward way is to call the
541 ``xpath()`` method on an Element or ElementTree::
542
543 lxe: xpath_method (--TC T1) 0.2828 msec/pass
544 lxe: xpath_method (--TC T2) 5.4705 msec/pass
545 lxe: xpath_method (--TC T3) 0.0324 msec/pass
546 lxe: xpath_method (--TC T4) 0.2804 msec/pass
547
548 This is well suited for testing and when the XPath expressions are as diverse
549 as the trees they are called on. However, if you have a single XPath
550 expression that you want to apply to a larger number of different elements,
551 the ``XPath`` class is the most efficient way to do it::
552
553 lxe: xpath_class (--TC T1) 0.0570 msec/pass
554 lxe: xpath_class (--TC T2) 0.6924 msec/pass
555 lxe: xpath_class (--TC T3) 0.0148 msec/pass
556 lxe: xpath_class (--TC T4) 0.0446 msec/pass
557
558 Note that this still allows you to use variables in the expression, so you can
559 parse it once and then adapt it through variables at call time. In other
560 cases, where you have a fixed Element or ElementTree and want to run different
561 expressions on it, you should consider the ``XPathEvaluator``::
562
563 lxe: xpath_element (--TR T1) 0.0684 msec/pass
564 lxe: xpath_element (--TR T2) 1.0865 msec/pass
565 lxe: xpath_element (--TR T3) 0.0174 msec/pass
566 lxe: xpath_element (--TR T4) 0.0665 msec/pass
567
568 While it looks slightly slower, creating an XPath object for each of the
569 expressions generates a much higher overhead here::
570
571 lxe: xpath_class_repeat (--TC T1 ) 0.2813 msec/pass
572 lxe: xpath_class_repeat (--TC T2 ) 5.4042 msec/pass
573 lxe: xpath_class_repeat (--TC T3 ) 0.0339 msec/pass
574 lxe: xpath_class_repeat (--TC T4 ) 0.2706 msec/pass
575
576 Note that tree iteration can be substantially faster than XPath if
577 your code short-circuits after the first couple of elements were
578 found. The XPath engine will always return the complete result set,
579 regardless of how much of it will actually be used.
580
581 Here is an example where only the first matching element is being
582 searched, a case for which XPath has syntax support as well::
583
584 lxe: find_single (--TR T2) 0.0031 msec/pass
585 cET: find_single (--TR T2) 0.0026 msec/pass
586
587 lxe: iter_single (--TR T2) 0.0019 msec/pass
588 cET: iter_single (--TR T2) 0.0002 msec/pass
589
590 lxe: xpath_single (--TR T2) 0.0861 msec/pass
591
592 When looking for the first two elements out of many, the numbers
593 explode for XPath, as restricting the result subset requires a
594 more complex expression::
595
596 lxe: iterfind_two (--TR T2) 0.0050 msec/pass
597 cET: iterfind_two (--TR T2) 0.0036 msec/pass
598
599 lxe: iter_two (--TR T2) 0.0021 msec/pass
600 cET: iter_two (--TR T2) 0.0014 msec/pass
601
602 lxe: xpath_two (--TR T2) 0.0916 msec/pass
603
604
605 A longer example
606 ================
607
608 ... based on lxml 1.3.
609
610 A while ago, Uche Ogbuji posted a `benchmark proposal`_ that would
611 read in a 3MB XML version of the `Old Testament`_ of the Bible and
612 look for the word *begat* in all verses. Apparently, it is contained
613 in 120 out of almost 24000 verses. This is easy to implement in
614 ElementTree using ``findall()``. However, the fastest and most memory
615 friendly way to do this is obviously ``iterparse()``, as most of the
616 data is not of any interest.
617
618 .. _`benchmark proposal`: http://www.onlamp.com/pub/wlg/6291
619 .. _`Old Testament`: http://www.ibiblio.org/bosak/xml/eg/religion.2.00.xml.zip
620
621 Now, Uche's original proposal was more or less the following:
622
623 .. sourcecode:: python
624
625 def bench_ET():
626 tree = ElementTree.parse("ot.xml")
627 result = []
628 for v in tree.findall("//v"):
629 text = v.text
630 if 'begat' in text:
631 result.append(text)
632 return len(result)
633
634 which takes about one second on my machine today. The faster ``iterparse()``
635 variant looks like this:
636
637 .. sourcecode:: python
638
639 def bench_ET_iterparse():
640 result = []
641 for event, v in ElementTree.iterparse("ot.xml"):
642 if v.tag == 'v':
643 text = v.text
644 if 'begat' in text:
645 result.append(text)
646 v.clear()
647 return len(result)
648
649 The improvement is about 10%. At the time I first tried (early 2006), lxml
650 didn't have ``iterparse()`` support, but the ``findall()`` variant was already
651 faster than ElementTree. This changes immediately when you switch to
652 cElementTree. The latter only needs 0.17 seconds to do the trick today and
653 only some impressive 0.10 seconds when running the iterparse version. And
654 even back then, it was quite a bit faster than what lxml could achieve.
655
656 Since then, lxml has matured a lot and has gotten much faster. The iterparse
657 variant now runs in 0.14 seconds, and if you remove the ``v.clear()``, it is
658 even a little faster (which isn't the case for cElementTree).
659
660 One of the many great tools in lxml is XPath, a Swiss army knife for finding
661 things in XML documents. It is possible to move the whole thing to a pure
662 XPath implementation, which looks like this:
663
664 .. sourcecode:: python
665
666 def bench_lxml_xpath_all():
667 tree = etree.parse("ot.xml")
668 result = tree.xpath("//v[contains(., 'begat')]/text()")
669 return len(result)
670
671 This runs in about 0.13 seconds and is about the shortest possible
672 implementation (in lines of Python code) that I could come up with. Now, this
673 is already a rather complex XPath expression compared to the simple "//v"
674 ElementPath expression we started with. Since this is also valid XPath, let's
675 try this instead:
676
677 .. sourcecode:: python
678
679 def bench_lxml_xpath():
680 tree = etree.parse("ot.xml")
681 result = []
682 for v in tree.xpath("//v"):
683 text = v.text
684 if 'begat' in text:
685 result.append(text)
686 return len(result)
687
688 This gets us down to 0.12 seconds, thus showing that a generic XPath
689 evaluation engine cannot always compete with a simpler, tailored solution.
690 However, since this is not much different from the original findall variant,
691 we can remove the complexity of the XPath call completely and just go with
692 what we had in the beginning. Under lxml, this runs in the same 0.12 seconds.
693
694 But there is one thing left to try. We can replace the simple ElementPath
695 expression with a native tree iterator:
696
697 .. sourcecode:: python
698
699 def bench_lxml_getiterator():
700 tree = etree.parse("ot.xml")
701 result = []
702 for v in tree.getiterator("v"):
703 text = v.text
704 if 'begat' in text:
705 result.append(text)
706 return len(result)
707
708 This implements the same thing, just without the overhead of parsing and
709 evaluating a path expression. And this makes it another bit faster, down to
710 0.11 seconds. For comparison, cElementTree runs this version in 0.17 seconds.
711
712 So, what have we learned?
713
714 * Python code is not slow. The pure XPath solution was not even as fast as
715 the first shot Python implementation. In general, a few more lines in
716 Python make things more readable, which is much more important than the last
717 5% of performance.
718
719 * It's important to know the available options - and it's worth starting with
720 the most simple one. In this case, a programmer would then probably have
721 started with ``getiterator("v")`` or ``iterparse()``. Either of them would
722 already have been the most efficient, depending on which library is used.
723
724 * It's important to know your tool. lxml and cElementTree are both very fast
725 libraries, but they do not have the same performance characteristics. The
726 fastest solution in one library can be comparatively slow in the other. If
727 you optimise, optimise for the specific target platform.
728
729 * It's not always worth optimising. After all that hassle we got from 0.12
730 seconds for the initial implementation to 0.11 seconds. Switching over to
731 cElementTree and writing an ``iterparse()`` based version would have given
732 us 0.10 seconds - not a big difference for 3MB of XML.
733
734 * Take care what operation is really dominating in your use case. If we split
735 up the operations, we can see that lxml is slightly slower than cElementTree
736 on ``parse()`` (both about 0.06 seconds), but more visibly slower on
737 ``iterparse()``: 0.07 versus 0.10 seconds. However, tree iteration in lxml
738 is incredibly fast, so it can be better to parse the whole tree and then
739 iterate over it rather than using ``iterparse()`` to do both in one step.
740 Or, you can just wait for the lxml developers to optimise iterparse in one
741 of the next releases...
742
743
744 lxml.objectify
745 ==============
746
747 The following timings are based on the benchmark script `bench_objectify.py`_.
748
749 Objectify is a data-binding API for XML based on lxml.etree, that was added in
750 version 1.1. It uses standard Python attribute access to traverse the XML
751 tree. It also features ObjectPath, a fast path language based on the same
752 meme.
753
754 Just like lxml.etree, lxml.objectify creates Python representations of
755 elements on the fly. To save memory, the normal Python garbage collection
756 mechanisms will discard them when their last reference is gone. In cases
757 where deeply nested elements are frequently accessed through the objectify
758 API, the create-discard cycles can become a bottleneck, as elements have to be
759 instantiated over and over again.
760
761
762 ObjectPath
763 ----------
764
765 ObjectPath can be used to speed up the access to elements that are deep in the
766 tree. It avoids step-by-step Python element instantiations along the path,
767 which can substantially improve the access time::
768
769 lxe: attribute (--TR T1) 2.4018 msec/pass
770 lxe: attribute (--TR T2) 16.3755 msec/pass
771 lxe: attribute (--TR T4) 2.3725 msec/pass
772
773 lxe: objectpath (--TR T1) 1.1816 msec/pass
774 lxe: objectpath (--TR T2) 14.4675 msec/pass
775 lxe: objectpath (--TR T4) 1.2276 msec/pass
776
777 lxe: attributes_deep (--TR T1) 3.7086 msec/pass
778 lxe: attributes_deep (--TR T2) 17.5436 msec/pass
779 lxe: attributes_deep (--TR T4) 3.8407 msec/pass
780
781 lxe: objectpath_deep (--TR T1) 1.4980 msec/pass
782 lxe: objectpath_deep (--TR T2) 14.7266 msec/pass
783 lxe: objectpath_deep (--TR T4) 1.4834 msec/pass
784
785 Note, however, that parsing ObjectPath expressions is not for free either, so
786 this is most effective for frequently accessing the same element.
787
788
789 Caching Elements
790 ----------------
791
792 A way to improve the normal attribute access time is static instantiation of
793 the Python objects, thus trading memory for speed. Just create a cache
794 dictionary and run:
795
796 .. sourcecode:: python
797
798 cache[root] = list(root.iter())
799
800 after parsing and:
801
802 .. sourcecode:: python
803
804 del cache[root]
805
806 when you are done with the tree. This will keep the Python element
807 representations of all elements alive and thus avoid the overhead of repeated
808 Python object creation. You can also consider using filters or generator
809 expressions to be more selective. By choosing the right trees (or even
810 subtrees and elements) to cache, you can trade memory usage against access
811 speed::
812
813 lxe: attribute_cached (--TR T1) 1.9207 msec/pass
814 lxe: attribute_cached (--TR T2) 15.6903 msec/pass
815 lxe: attribute_cached (--TR T4) 1.8718 msec/pass
816
817 lxe: attributes_deep_cached (--TR T1) 2.6512 msec/pass
818 lxe: attributes_deep_cached (--TR T2) 16.7937 msec/pass
819 lxe: attributes_deep_cached (--TR T4) 2.5539 msec/pass
820
821 lxe: objectpath_deep_cached (--TR T1) 0.8519 msec/pass
822 lxe: objectpath_deep_cached (--TR T2) 13.9337 msec/pass
823 lxe: objectpath_deep_cached (--TR T4) 0.8645 msec/pass
824
825 Things to note: you cannot currently use ``weakref.WeakKeyDictionary`` objects
826 for this as lxml's element objects do not support weak references (which are
827 costly in terms of memory). Also note that new element objects that you add
828 to these trees will not turn up in the cache automatically and will therefore
829 still be garbage collected when all their Python references are gone, so this
830 is most effective for largely immutable trees. You should consider using a
831 set instead of a list in this case and add new elements by hand.
832
833
834 Further optimisations
835 ---------------------
836
837 Here are some more things to try if optimisation is required:
838
839 * A lot of time is usually spent in tree traversal to find the addressed
840 elements in the tree. If you often work in subtrees, do what you would also
841 do with deep Python objects: assign the parent of the subtree to a variable
842 or pass it into functions instead of starting at the root. This allows
843 accessing its descendants more directly.
844
845 * Try assigning data values directly to attributes instead of passing them
846 through DataElement.
847
848 * If you use custom data types that are costly to parse, try running
849 ``objectify.annotate()`` over read-only trees to speed up the attribute type
850 inference on read access.
851
852 Note that none of these measures is guaranteed to speed up your application.
853 As usual, you should prefer readable code over premature optimisations and
854 profile your expected use cases before bothering to apply optimisations at
855 random.