Performance
go-xslt is compared here with xsltproc and xmllint, the command-line tools of libxslt and libxml2, the C libraries most XML tooling is built on. Both run the same XSLT 1.0 stylesheets on the same document, so they do the same work; each run is timed as a whole process (start, parse, transform, serialize).
Apple M4, macOS, libxml2 2.9.13 / libxslt 1.1.35; input 200,000 records, 37 MB; median of 5 runs.
| Workload | go-xslt | libxslt / libxml2 | ratio | peak memory go-xslt | peak memory libxml2 |
|---|---|---|---|---|---|
| copy the whole document | 0.43 s | 0.69 s | 0.62× | 1,106 MB | 1,067 MB |
| recursive apply-templates, rebuilding every node | 0.84 s | 1.23 s | 0.68× | 1,134 MB | 1,074 MB |
| sort all records by two keys, text output | 0.54 s | 18.66 s * | — | 761 MB | 587 MB |
Muenchian grouping with xsl:key | 0.51 s | 0.87 s | 0.59× | 784 MB | 538 MB |
| predicates, string and number functions | 0.44 s | 0.83 s | 0.53× | 712 MB | 590 MB |
| XSD 1.0 validation | 0.42 s | 0.51 s | 0.81× | 593 MB | 539 MB |
* Not a sorting measurement. Almost all of libxslt's time here goes into building the 5.6 MB text output: the libxslt 1.1.35 that macOS ships appends each piece to one text node and measures that node's whole length again every time, which grows quadratically. The same stylesheet without xsl:sort takes it just as long; the sorting itself costs libxslt about 1.5 s. Current libxslt releases avoid this, so the row is left out of the comparison.
The machine was not idle during this run, which slows both tools alike; the ratios are what carries over.
Reading the numbers
- go-xslt is faster than the C libraries on every workload both can run, validation included. It needs somewhat more memory for the document tree.
- The comparison is limited to what both can do. go-xslt also implements XSLT 3.0, XPath 3.1 and XSD 1.1, which libxslt and libxml2 do not.
- For documents too large for memory, XSLT 3.0 streaming processes them in a few megabytes, whatever their size.
- A program that runs the same stylesheet many times should compile it once; the numbers above include compiling the stylesheet on every run.
Where the time goes
Six rounds of profiling and measurement brought go-xslt from 1.5–4.5 times libxslt's time to where it is now:
reusing evaluation contexts (per predicate, key walk, template match and XPath evaluation) instead of allocating one per node, carving parsed nodes from blocks, and matching XSD content models without per-element maps;
an own XML tokenizer in place of
encoding/xmlthat hands out pieces of the document instead of copies — it accepts and rejects exactly whatencoding/xmldid, which differential fuzzing and the W3C XML Conformance Test Suite check — about 260 MB less per 37 MB document;skipping the DTD passes for documents without a DOCTYPE, fewer allocations per template call, and serializing without building strings;
matching simple patterns such as
node()and@*without a full evaluation context, keepingdeferout of the hottest functions, and a faster sort where the result is provably the same;normalizing whitespace in attribute values only where an attribute value actually contains a tab or line break, writing parsed nodes straight into their blocks, numbering document order while parsing, and building copies from per-run blocks;
for XSLT 3.0:
xsl:for-each-group group-byfiles its groups by key instead of comparing every item with every group so far (5× faster with 5,000 groups); maps are persistent hash tries, somap:putno longer copies the whole map, andarray:appendappends in place — collecting one entry per record inxsl:iteratewas quadratic and is now linear (5,000 keys over 20,000 records: 53 s before, 0.4 s now); a typed parameter is bound without parsing itsastype again on every call, and built-in functions convert their arguments with fewer allocations (12 % less time for a transform made of function calls).a seventh round, with a committed A/B harness (
scripts/perfab) that runs 23 workloads on two builds — timed, and counted in instructions under cachegrind where the machine is too noisy to time — and passes a change only if no workload gets slower, bigger or different:xsl:numberbuilds one evaluation context per numbering instead of one per candidate node (numbering 2,000 records withcount="order|item": 3.3 s and 3.5 GB allocated before, 0.55 s and 8 MB now); anarray(xs:string)parameter accumulated witharray:appendinxsl:iteratewas re-checked member by member on every step — the shared array now remembers the verified prefix, so 20,000 records take 0.2 s instead of 8.5 s; and matching a single item against a declared type no longer boxes it into a slice (one allocation less per typed parameter, variable or result binding).the eighth round, on the validator, the readers and the string functions, judged by instructions executed under cachegrind and by allocations, since the machine could not time the change (two runs of the same build differed by up to 15 %): an XSD 1.1 assertion is evaluated against a detached copy of its element, which is now carved from two slabs instead of one allocation per node, with one annotation lookup per element or attribute instead of two per node, and identity constraints no longer rebuild a content-model map for every node a selector picks (XSD 1.1 validation of the 200,000-order document: 20 % fewer allocations, 9 % fewer instructions); the streaming reader allocates an element together with its attributes (8 % fewer allocations in the streaming workload);
fn:string-joinjoins nodes without atomizing them into a new sequence,fn:normalize-spacereturns an already-normalized string as it is,fn:upper-case/lower-casetake an ASCII path,fn:tokenize/replace/analyze-stringdecide "matches the empty string" once per pattern andformat-datereads its picture by byte (the function-call workload: 7 % fewer instructions and allocations; the string workload: 4 % fewer instructions, 6 % fewer allocations, 40 MB less allocated);fn:json-to-xmlbuilds its tree from slabs with children slices made to size (6 % fewer allocations in the JSON round trip); and indentation is written from a constant instead of a string per element. No workload executes more instructions than before, and every output is byte-identical.a ninth round, on the evaluation context and the value model: the static base URI of an expression (the
xml:basechain above its element in the stylesheet, whichdoc(),document(),unparsed-text(),static-base-uri()and a few others read) was walked before every evaluation of every expression in a stylesheet loaded from a file; it is now computed when one of those functions asks for it (HTML output workload: 4 % fewer instructions); and four places that turned a node set into a boxed sequence of items —fn:subsequence, matching a node set against a declared type, the string of a one-itemxsl:value-ofor attribute value template, andcurrent-group()— now work on the node set itself (deep named-template recursion: 9 % fewer instructions, 5 % fewer allocations; 200 transforms in one process: 5 % fewer instructions, 9 % fewer allocations; the function-call workload: 3 % fewer allocations; the regular-expression workload: 4 % fewer). No workload executes more instructions than before, and every output is byte-identical.a tenth round, in two parallel halves. The validator's half: an XSD 1.1 assertion is evaluated against a detached copy of its element, and that copy was carved from two fresh slabs per element, every typed node in it got a node extension of its own, and every assertion allocated an evaluation context, a variable resolver and an empty
$value; the copy now comes from one arena the validation call keeps — reset for every element, its slabs grow to the largest tree and then serve every later one, with a third slab for the extensions, sized by the same walk that already counts the nodes and now also looks each one's type annotation up once — and one context and resolver are reused until a function item captures them. Identity constraints reuse one context the same way, take the evaluator's node set as it is instead of copying it, and build each key tuple field by field in one buffer (a string-typed field appended directly, since its cast hands the lexical back unchanged) instead of one string per field plus one for the join; and the per-element count of children that XSD 1.1's dynamic Element Declarations Consistent check needs is kept only where the content model has a lax or strict wildcard, the only case that ever reads it. XSD 1.1 validation of the 200,000-order document: a third fewer allocations, 60 % fewer bytes allocated, 9 % fewer instructions, 11 % less peak memory. No workload executes more instructions than before, and every output is byte-identical. Tried and dropped: carving the streaming reader's nodes from shared slabs would have saved a fifth of that workload's allocations, but a slab is one object to the collector, so the dead records sharing a slab with a live one kept their own children — and, slab by slab, the whole document — reachable; the memory-bound tests caught it (1.2 GB peak for 82 MB of input where 0.1 MB is the norm). Also dropped: a non-recursive walk for the XSD 1.0 schema-location-hint check, which saved 0.1 % of the instructions and cost an 8 MB stack of child pointers.a tenth round, part A, on the evaluator and the serializer, under the same harness and the same rule (no workload may allocate more, grow or execute more instructions): the html serializer parsed the usually empty html-version string for every element to decide prefix normalization, allocating a parse error each time — it is decided once per serialization (HTML output workload: 3 % fewer instructions, 7.5 % fewer allocations); an attribute value template is built in one allocation from parts collected on the stack, and a one-expression template is its part's own string (HTML: 8 % fewer allocations; 200 transforms in one process: 3.5 % fewer); the backwards-compatibility scope of an instruction (its ancestors'
[xsl:]versionattributes) is remembered per run instead of walked for every xsl:value-of, attribute value template, xsl:number and xsl:call-template under a version="1.0" stylesheet; xsl:value-of and xsl:sequence check a node-set result for map or function items without boxing it, and a literal result element's children are rebuilt only when there is an empty text node to drop (HTML: 7 % fewer allocations); an xsl:key index whose pattern can match elements only is built over the elements alone — the attributes and text nodes, most of the tree, were each handed to the matcher to be rejected by kind; a template or function call starts its callee with the caller's spare scope-stack capacity, the context a declared type is matched in is remembered per run, and the key of a stylesheet function is one concatenation; the simple map operator, a postfix path step and a predicate over non-node items reuse one evaluation context per loop, as predicates over nodes already did, replaced only once a function item captured it (grouping into a map with JSON output: 8 % fewer bytes allocated); and the apply-templates select@*|node()hands its node set back without boxing it into an interface, which was 94 % of the allocations of the template-dispatch workload. No workload executes more instructions than before, and every output is byte-identical.an eleventh round, part A, on the evaluator, the value model and the functions, under the same harness and rule: a node test (128 bytes) was copied three times for every candidate node of every axis step and pattern match, and xsl:number asked its count pattern for every candidate whether it needs a full context — numbering 2,000 records with position()/last(): 31 % fewer instructions, and 2–4 % fewer in every workload that walks axes; a
forexpression reuses one context per loop and a result's items are appended without boxing a single item first; a template or function frame keeps its bindings in a short slice instead of a map; format-date's plain digit pictures ([D01], [Y0001]) are formatted without parsing them into maps; a valid JSON text is tokenized in place rather than through json.Decoder.Token, which decoded every scalar through Decode and built a syntax error it discarded for each (JSON round trip: 40 % fewer instructions, 45 % fewer allocations, 20 % less bytes allocated; a text the Decoder rejects still goes through it for its error); a value comparison and a built-in's string argument atomize a singleton without building a sequence, a small integer cast from a lexical reuses the cached Atomic, a plain decimal lexical becomes a Rat from an int64 mantissa (XSD 1.1 assertions over the 200,000-order document: 10 % fewer instructions, 28 % fewer allocations); concat and string-join build their result in one allocation; xsl:next-iteration no longer panics and recovers once per iteration to compare two errors; a map key's category sits beside its string instead of being prefixed to it (one concatenation less per map operation on a string key); and tokenize on a pattern of plain characters splits on the string. The function-call workload: 16 % fewer instructions, 29 % fewer allocations; deep recursion: 15 % fewer instructions; iterating over maps: 12 % fewer instructions; the string workload: 6 % fewer instructions, 18 % fewer allocations. No workload allocates more; the one workload that executes more instructions is the key lookup one, 0.6 % more against 2 % fewer allocations, from the one-allocation concat. Every output is byte-identical. Tried and dropped: handing key()'s result out as the index's own list (the receiver may reuse a node set as a buffer, and did), and a SERE0006 scan that read a result tree eight bytes at a time — ordinary output is full of newlines, each of which tripped the word test, so it executed more instructions than the byte loop it replaced.an eleventh round, part B, on the readers, the compiler and the validator (part A, in parallel, took the evaluator). The streaming reader read its tokens through
encoding/xml, which allocated for every one of them — the boxed token, a copy of every name, attribute value and text run, the attribute list — half of a streamed transformation's allocations; it now runs the engine's own tokenizer over a window of the input (a token that reaches the window's end is scanned again once more input is read, so every token arrives whole), and a streamed record's strings are pieces of that window (streaming the 200,000-record document: 65 % fewer allocations, a fifth less allocated, 55 % fewer instructions, half the time; the memory bound is unchanged, and the reader is checked against the buffered parser at every window size from one byte). Compiling a stylesheet parsed every included or imported module twice — once to establish the static parameters across modules, once to compile it — and now hands the first tree to the second pass; the compiler also stops copying every element's attribute list and child list it does not change, and sizes an instruction list once (compiling the DocBook stylesheets: 30 % fewer instructions, a fifth fewer allocations, 38 % less allocated). XSD 1.1 validation recorded the typed-value annotation of every simple-typed node of the instance in one map for its assertions to read, 2.4 million entries for the 200,000-record document; the map is now emptied whenever no open element has assertions, so it stays the size of one record (6 % less allocated, 2 % less peak memory, 2 % fewer instructions). The parser resolves an unprefixed element name without a map lookup, and the serializer decides the output version once, keeps the default namespace in a field instead of a map entry, and checks whether a value needs escaping with a table instead of building a character set per call (copying the whole document: 11 % fewer instructions; rebuilding every node: 6 %; the HTML output workload: 4 %). No workload executes more instructions than before, and every output is byte-identical.a twelfth round, part A, on the evaluator and the XSLT instructions, under the same harness and rule: a path expression's node set was boxed into an interface value every time it was evaluated — one allocation per predicate, comparison operand, function argument, select, test, value-of and attribute value template, 16 % of all allocations of an XSD 1.1 validation and 29 % of the XPath 1.0 predicate workload — and the consumers that only read the nodes now take the set itself (a predicate that is a path is an existence test; a comparison atomizes the set directly; a built-in's path argument is converted to the declared atomic type on the spot, exactly as the argument check would convert the boxed set, so the check then finds it matching; count, exists, empty, boolean and not are answered from the set; xsl:for-each runs over the set without copying it twice; a key index takes each node's key string from it); the arguments of the string, number, date-component, aggregate and node-name built-ins live on a per-evaluation stack instead of a slice allocated per call (the implementations were read one by one: none keeps its argument slice); five one-item argument helpers (string-length and friends, fn:string, the xs: constructors, a plain Go string argument, string-join over tokenize's strings) no longer build a sequence or an Atomic to read one value from it; a
forexpression reads its binding sequence in place and starts its result at the right size; a 1.0-compatible arithmetic operand and an xsl:sort key are atomized without a one-item sequence; and xsl:next-iteration hands its values on in a slice, not a map. What a call can do without boxing is decided once per call node, so a call that can do nothing of it costs one load — the first version decided it per call and added call frames on the hottest paths, which cachegrind showed as 1.7 % more instructions on the string workload with no allocation saved; every such frame was removed before anything was kept. The function-call workload: 10 % fewer instructions, 31 % fewer allocations, 18 % fewer bytes allocated; the string workload: 6 % fewer instructions, 31 % fewer allocations; key lookups: 5 % fewer instructions, 23 % fewer allocations, 9 % less peak memory; XSD 1.1 assertions over the 200,000-order document: 4 % fewer instructions, 20 % fewer allocations; the XPath 1.0 predicate workload: 28 % fewer allocations; HTML output: 16 % fewer allocations. No workload allocates more or executes more instructions beyond the counter's spread, and every output is byte-identical.a twelfth round, part B, on the readers, the validator and the compiler (part A, in parallel, took the evaluator). The streaming reader allocated a child list for every element that had any children, most of them leaves holding one text node; a streamed element's allocation now carries the slot for its first child, which costs nothing — a node is 152 bytes, so an element with up to three attributes ended 8 bytes short of its allocation size class — and the reader keeps one frame per open element in place of three stacks (streaming the 200,000-record document: 17 % fewer allocations, 5 % fewer instructions). The parser looked every token's line and column up, scanned each element's attributes a second time for xml:space, and kept six parallel stacks of what it knows about the open elements; it now looks a position up only where a node or an error message keeps it, notes xml:space while it resolves the attributes, and keeps one frame per open element (copying the whole document: 5 % fewer instructions; every workload that parses the large document 2–5 % fewer). The validator found an element's xsi:type and xsi:nil, and the XSD 1.0 schema-location hints, with one pass over the attributes per name, and looked each child's declaration up by hashing its name; it now finds them in one pass, and a content model of up to eight declared names is searched as a list kept in the model itself (XSD 1.0 validation of the 200,000-order document: 7 % fewer instructions in all, with the parser's share). The compiler asked, for every whitespace-only text node of a stylesheet, whether xml:space preserves it by walking its ancestors; it asks once per parent element (compiling the DocBook stylesheets: 3 % fewer instructions). No workload executes more instructions than before, and every output is byte-identical. Tried and dropped: lower-casing each attribute name once in the HTML serializer saved 1 % on the HTML workload but cost the xml output method a check per attribute (0.5 % more instructions on the identity workload).
a thirteenth round, part A, on the value model, the functions and the XSLT instructions, under the same harness and rule: an xs:decimal was a big.Rat — three to five allocations to read one from a lexical, as many for every sum or product, a dozen to format one — and is now held compactly, as an int64 mantissa and a scale inside the same 64-byte Atomic, whenever its value fits (a repeating quotient or more than 18 digits keeps the Rat), with addition, subtraction, multiplication, rounding, comparison, casting and formatting done in integers and checked against the Rat path to the bit over 435 lexicals pairwise (deep recursion summing decimals: 13 % fewer instructions, half the allocations; xsl:iterate with a decimal map: 13 % fewer instructions, 29 % fewer allocations; XSD 1.1 assertions: 3 % fewer instructions); format-number renders a compact decimal or an int64 integer in integer arithmetic (number formatting: 27 % fewer instructions, 48 % fewer allocations; 200 transforms in one process: 15 % fewer); an xsl:sort key that selects one unannotated node is classified from the node, without boxing the set or atomizing it (sort: 5 % fewer instructions, 46 % fewer allocations, with the next item); a string parameter's one plain node is passed as the bare node instead of a set around it, in 1.0 compatibility mode too (the string workload: 11 % fewer allocations; the XPath 1.0 predicate workload 24 %, regular expressions 12 %); key() keeps its search values on the stack; a call chain's scope stack and a function call's frame are kept for the next call (the function-call workload: 5 % fewer allocations); and generate-id returns its id as the plain string (Muenchian grouping: 3 % less allocated). No workload allocates more or executes more instructions beyond the counter's spread. Every output is byte-identical.
a thirteenth round, part B, on the readers, the validator and the serializer (part A, in parallel, took the evaluator). A streamed element's allocation already carried its attribute nodes and the slot for its first child; when the input shows character data right after the start tag, the shapes with up to two attributes now carry the node for that first text child too — a text node alone took a 160-byte allocation, and each shape with one more node ends in the class the two took together, so a leaf record costs one allocation less for the same bytes, and nothing lives longer, since the element and its text child keep each other alive anyway (streaming the 200,000-record document: 15 % fewer allocations, 2 % fewer instructions; the memory bound is unchanged). The validator's identity constraints evaluated every selector and field through the boxing evaluator, built a string for every key tuple to insert it and another to look it up, resolved a field's type twice and memoised the type of every leaf element; they now take a path's node set as it is, keep the tuples of a table in one byte arena and look a tuple up in place, resolve the type once, and memoise only the elements a later lookup can walk through — and the assertions' built-in calls push their arguments on a per-call stack instead of allocating a slice each (XSD 1.1 validation of the 200,000-order document: 17 % fewer allocations, 7 % less allocated, 5 % fewer instructions). XSD 1.0's rule on late schema-location hints was enforced by a walk over the whole instance that recorded every namespace, for every validation; a hint on the document element itself can never break the rule, so the walk now runs only when a cheaper scan finds a hint below the root, and an attribute use is marked present by the position its lookup found instead of a second search (XSD 1.0 validation of the same document: 4 % fewer instructions). The html serializer looked an element's URI-valued attributes up for every attribute, lower-casing the names twice; it looks them up once per element, outside the xml method's path — the first version put one test per element on that path too, and cachegrind showed it as 0.4 % more instructions on the identity workload — and the content opener of an element is written without concatenating (HTML output: 4 % fewer instructions; copying the whole document: 1.5 %; rebuilding every node: 1 %). No workload executes more instructions than before beyond the counter's spread, none allocates more, and every output is byte-identical.
a fourteenth round, part A, on the evaluator, the value model and the key index, under the same harness and rule: a path of one predicate-free child or attribute step ("@id", "customer") allocated its node set on every evaluation, although most readers of such a set drop it at once — a built-in's argument converted to its declared type, count and the other node-set tests, a predicate's existence test, a comparison's operand, xsl:value-of, an attribute value template, xsl:if, a key's use, a sort key — and these now build the set in one scratch array the evaluation owns (the step itself evaluates nothing, so nothing can run between building and reading it; the few readers that pass the set on detach a copy), which fused arguments have that shape being decided once with the call's plan (sort: 6 % fewer instructions, 60 % fewer allocations; the XPath 1.0 predicate workload 3 % and 49 %; regular expressions 3 % and 30 %; the string workload 5 % and 18 %; HTML output 6 % and 16 %; streaming 3 % and 12 %; XSD 1.1 assertions 2 % and 10 %); an xs:integer was a big.Int — an allocation or two for every position(), count, sum and parsed lexical, three to format one — and is now held compactly as an int64 inside the Atomic whenever its value fits, with addition, subtraction, multiplication, idiv, mod, sum, comparison, casting, formatting and the map key done in integers, every overflow checked and sent to big.Int, and an integer div whose quotient terminates computed as the compact decimal directly, all checked against the big.Int path pairwise over the int64 boundaries (key lookups: 7 % fewer instructions and 31 % fewer allocations with the two items around it; number formatting 4 % and 13 %); a large key index takes each entry's first slot from a shared 512-byte chunk — a larger chunk carries Go's allocation header and lands in the next size class, which cost 380 KB over the keys workload before it was measured, and a field more on the engine struct, 1,024 bytes, the end of its class, cost 128 bytes per run; string(customer) and xs:decimal(price) — fn:string or a constructor over a one-step path — pass the path's one node as the bare node, with the set and the argument slice on the scratch stack (xsl:iterate with a decimal map: 5 % fewer instructions, 15 % fewer allocations; group-by with JSON output 3 % and 10 %; 200 transforms in one process 3.5 % and 13 %); a value converted to a declared atomic type atomizes a node item without a one-item sequence around it (deep recursion: 1 % fewer instructions, 10 % fewer allocations); and a JSON object being built grows two lists instead of three, the marks for pre-escaped keys existing only once one is marked (the JSON round trip: 3 % fewer instructions, 6 % fewer allocations). No workload allocates more or executes more instructions beyond the counter's spread, and every output is byte-identical.
a fourteenth round, part B, on the readers, the serializer, the validator and the compiler (part A, in parallel, took the evaluator), under the same harness and rule. The serializer wrote a start tag as four calls to the output writer, its ">" as a fifth and an end tag as three more, each indentation line break and run of spaces another: an element cost eight to ten calls through the writer interface, 9 % of the instructions of a copy of a large document. Each tag now reaches the writer in one call, built in the scratch buffer the attributes already used (copying the whole document: 6.6 % fewer instructions; rebuilding every node: 3.3 %; HTML output: 2.3 %; streaming 1.1 %; 200 transforms in one process: 1 %). The tokenizer's read of one structural byte could not be inlined, so a start tag cost a call per byte between its names and values; the common case is inlined at those sites (copying the whole document: 2.7 % fewer instructions; XSD validation 2.4 %, the XPath 1.0 predicates 2.6 %, streaming 3 %, template dispatch 1.3 %, compiling the DocBook stylesheets 1 %). The parser looked three DTD tables up for every element, attribute and text run of a document without a DOCTYPE, and found a token's line with one search call per line; the lookups now run only with a DOCTYPE, and a span of up to 16 bytes — the indentation between two tags — is read by a byte loop while a longer one keeps the library search (together 1.2 % fewer instructions copying the document, 1 % validating it, 0.7 % compiling the stylesheets; a first version counted a span's line breaks with strings.Count and walked back to the last one, which cost the long lines of a stylesheet 0.4 % and was taken out again). Both readers shared the indentation runs through a map, one lookup per run; the run last seen of each length answers nearly every run with one comparison (0.3 %). The streaming reader looked the default namespace up for every unprefixed element, asked its nil DTD tables all the same, and checked every attribute value for a tab or line break with strings.ContainsAny, which tests a short value byte by byte against the three characters: it keeps the default namespace in its frame and scans with a byte loop (streaming the 200,000-record document: 8 % fewer instructions). Under the html method every text node and attribute value was decoded rune by rune for a C1 control and every attribute name lower-cased through a call; one byte search (0xC2, the lead byte of U+00A0 and of every C1 control) gates the nbsp mapping and the C1 scan, and a lower-case ASCII name is returned after one look (HTML output: 1.1 %). The validator made two maps for every element validated — the derivation-chain guard of the effective attributes and particle, and the identity-constraint scope table — and a new map, even one that never leaves the stack, draws a hash seed from the runtime's random source; an underived type answers at once, a derived chain is guarded by a list on the stack, and the scope table exists only for an element declared with constraints (XSD 1.0 validation of the 200,000-order document: 3 % fewer instructions; XSD 1.1: 1.3 %). A simple type's primitive and whitespace handling, walked down the base chain several times for every value, are recorded once when the schema is compiled (1.5 % and 0.7 %). The use-when pruning walk of the compiler passes a text node without two calls (0.8 %). Over the whole round, against the version before it: copying the whole document executes 10 % fewer instructions, streaming 12 %, XSD 1.0 validation 8 %, template dispatch and HTML output 5 %, regular expressions 4 %, the XPath 1.0 predicates, sorting and XSD 1.1 validation 3.4 to 3.7 %, compiling the DocBook stylesheets 2.5 %, and every other workload between 0.1 % and 3.3 %. No workload executes more instructions than before beyond the counter's spread, none allocates more, and every output is byte-identical. Tried and dropped: a branch-free gathering of a text run's byte classes in the tokenizer (an OR per byte cost 0.3 to 0.5 % more than the predicted branch it replaced, on every workload that parses); noting a name's colon while the name is read, to spare the search for one (a stylesheet's names are mostly prefixed, so the per-byte test was added and the search still ran: 0.9 % more on the compile workload); a substring pre-check before the XSD 1.0 year-zero rule (two strings.Contains per value cost 3 % more than the short type walk they were to spare); and jumping from tag to tag with strings.IndexByte in the attribute-whitespace normalization (the text between a stylesheet's tags is a few bytes; the call cost more than the byte loop).
a fifteenth round, part A, on the evaluator, the value model and the XSLT instructions, under the same harness and rule. A path of several steps built the node set of every step as its own, and a step over several context nodes a set per node copied into the step's; the sets of the steps another step follows are now built in two arrays the evaluation scratch lends in turns, a step's nodes are appended straight into the one being built, and the last step's set is built where its reader wants it — the scratch array the readers of a one-step path already use (a fused built-in argument, fn:string's and a constructor's bare argument, count and the set tests, a comparison's operand, a path predicate, xsl:value-of, attribute value templates, tests and keys) — or copied out once at its final size (typed functions over the record: 11 % fewer allocations from the first, 10 % more from the second; string functions 23 %; the XPath 1.0 predicates 24 %; XSD 1.1 assertions 6 % and 3 %; deep recursion 8 %; group-by 7 %; 200 transforms in one process 9 %). A decimal quotient went through big.Rat even where it terminates, and fn:sum over decimals added every operand as a Rat before compacting the result: div, idiv and mod divide the compact mantissas (a Rat only for a repeating quotient), sum keeps a running int64 while nothing overflows and avg divides it, every path falling back to the Rat and checked against it pairwise (group-by with JSON output: 40 % fewer allocations; number formatting 5 %). Muenchian grouping, generate-id(.) = generate-id(key('k', x)[1]), built two id strings per test only to compare them; the parser marks such a comparison and it is answered from the nodes — an id is the tree root, the document order and a namespace node's prefix, so two are equal exactly when those are, "" only to another empty argument — with every unusual case left to the functions (the Muenchian workload: 9 % fewer instructions, 27 % fewer allocations). xsl:for-each-group's group-by boxed, atomized and bucketed every item's key and scanned the bucket; under the codepoint collation every string in a bucket is the same key as every other, so a key that is one plain node finds its group by the node's string value in a map of the string class alone, building an atom only for a new group (group-by with JSON output: 58 % fewer allocations; 200 transforms in one process 12 %). A for or quantified expression made a binding per item and a context per loop; the argument stack now counts the captures of every context sharing it, so the loop rebinds one binding in place while no function item was made during the body, and the per-item loops lend their scratch contexts from a pool (typed functions: 4.5 % fewer allocations and 9 % fewer bytes; the JSON round trip 1.5 % and 6.5 %). A plain node cast to a numeric or date/time type, an xs:string argument given as a plain node or a plain string, an arithmetic operand that is an atomic value and a map call's key skip the intermediate atom (xsl:iterate with a decimal map: 15 % fewer allocations; string functions 15 %; group-by with JSON output 20 %; number formatting 12 %; deep recursion 9 %). An xsl:iterate iteration keeps its scope frame for the next one under the capture-generation rule a function call's frame already follows, and xsl:next-iteration travels as a pointer holding the values of up to two parameters itself (the decimal map: 7 % fewer allocations; the array: 24 %). And xsl:number's walk over the preceding siblings was quadratic over a long sibling list numbered node after node; the run remembers, per instruction and parent, the last sibling it numbered and counts on from there whenever the match is a function of the node alone (xsl:number with position()/last() over 2,000 records: 0.37 s to 0.08 s of CPU, 80 % fewer instructions). A map called as a function, $m($k), allocated an argument slice, a table of argument holes and an item slice around the map to count it, and a literal predicate over a sequence, ($m($k), 0)[1], built a context per item: the one argument of a map call is the key, the hole table exists only for a partial application, the literal indexes the sequence, a sequence constructor starts with room for its parts, and xsl:iterate's loop reads the next-iteration sentinel by a type assertion where errors.As had allocated its target per iteration (the decimal map: 31 % fewer allocations; the array 16 %; typed functions 5 %). Over the whole round, against the version before it: xsl:number with position()/last() executes 80 % fewer instructions, group-by with JSON output 16 %, xsl:iterate with a decimal map 14 %, the Muenchian grouping 9.5 %, number formatting 7 %, typed functions 6.7 %, the string functions 5.7 %, 200 transforms in one process 5.5 %, xsl:iterate with an array 4.4 %, deep recursion 1.5 %, regular expressions and the JSON round trip 1.1 %, and the rest between 0 and 0.6 %; allocations fall by half on group-by with JSON output, by 43 % on the decimal map, by a third on the string functions, by 27 to 30 % on typed functions, the array, 200 transforms in one process and Muenchian grouping, by a fifth on the XPath 1.0 predicates, number formatting and regular expressions, and by 17 % on deep recursion. No workload executes more instructions than before beyond the counter's spread (0.3 % tonight between two runs of one binary), none allocates more, and every output is byte-identical. Tried and dropped: copying a path's last step set always (a 200,000-node set copied: 1.6 MB more on two workloads), copying a single-node non-direct step's set into the lent array (160 KB more on the JSON round trip), and keeping a last-step set beyond the pool's bound as the scratch (a reader passing a large set on copied it: 0.9 MB more on the XPath 1.0 predicates).
a fifteenth round, part B, on the validator, the readers, the serializer and the compiler (part A, in parallel, took the evaluator), under the same harness and rule. The validator asked, for every attribute use of every element, whether the use's own attribute was present by scanning every use for its name, twice; the use's position answers. Its linear content-model matcher compared a child's name with an element particle twice, once to see whether the particle could start and once to consume the child; one comparison does both. A simple type the compiled schema records knows whether its facets constrain anything, whether the XSD 1.0 year-zero rule has anything to look at for its primitive, and its whiteSpace mode as a constant, so the four facet checks, the rule and a switch on the mode's name are skipped where they decide nothing; the error location is stamped by a wrapper instead of a deferred call per element, the open-content chain is guarded by a list on the stack instead of a map per element, an element's child model is looked up once instead of three times, and its child elements and character data are found in one pass (XSD 1.0 validation of the 200,000-order document: 12.3 % fewer instructions, then 0.5 %; XSD 1.1: 4.3 %, then 0.5 % and 0.1 %). The parser scanned every attribute value of every start tag for a tab, LF or CR to decide whether its lazy whitespace pre-pass has to run, and the streaming reader scanned them again to normalize; the tokenizer's fast path classifies every byte of a value anyway, so a tab or line feed is now a byte the value needs a look for, and only the rare value that needed one is scanned. The tokenizer's white-space skip takes one table look per byte instead of a four-way comparison (and is inlined at the start-tag sites), both readers' open frames are filled in place instead of appended as a literal copied from the stack, and the parser's pending text run is flushed only when one is open (copying the whole document: 2.7 % fewer instructions; XSD 1.0 validation 2.6 %; compiling the DocBook stylesheets 1.7 %; keys 1.5 %; template dispatch 1.4 %; streaming 1.2 %). Both readers read a token from the tokenizer's own fields instead of a copy made for every tag, and the streamed retry restores only its position (copying the whole document: 1.2 %; XSD 1.0 validation 1 %); the ID normalization of an ordinary attribute returns from an inlined test (0.6 % and 0.5 %); an element or attribute name is read without the call between nsname and readName (copying the whole document 0.9 %, XSD 1.0 validation 0.9 %, streaming 0.9 %); and a name's bytes are read with one table look each instead of two comparisons, the high bits gathered by an OR telling afterwards whether the name was all ASCII (0.4 % on every workload that parses the document). The streaming reader interned every element name through a map; a 64-slot cache in front of it, indexed by the name's length and first and last bytes, answers a recurring name with one comparison (streaming the 200,000-record document: 2.8 % fewer instructions), and its prefix-undeclaring check is made where the declarations are found (0.3 %). The html output method looked every attribute name up in the boolean-attribute map and, for an element with URI-valued attributes, in that element's map; both are string switches now (HTML output: 5.9 % fewer instructions), and the serializer decides the output method and the normalization form once instead of comparing their names for every element and value (copying the whole document: 0.5 %). The compiler's attribute-set and call-template reference checks walk the stylesheet once instead of twice, with the error reported for any stylesheet unchanged, and white-space-only text is judged by a table (compiling the DocBook stylesheets: 0.8 % fewer instructions); the ASCII rows of the name-character predicates the XPath lexer asks for every character of a name are tables (1.1 %); an element's shadow attributes and use-when are found in one pass over its attributes (0.7 %); and a literal result element's ambient namespaces are gathered into a reused list, with exclude-result-prefixes parsed once per declaring element instead of once per literal result element (1.2 % fewer instructions, 2.1 % fewer allocations). Over the whole round, against the version before it: XSD 1.0 validation executes 17 % fewer instructions, the HTML output, streaming, compiling a stylesheet and XSD 1.1 validation 6 to 7 % fewer, copying a document 5 % fewer and the key lookups 3 % fewer (the cumulative per-candidate counts; the whole-round table was measured on the tree combined with part A). No workload executes more instructions than before beyond the counter's spread, none allocates more, and every output is byte-identical. Tried and dropped: comparing an XSD name's local part before its namespace (0.25 % more on XSD 1.0 validation: an equal-length empty namespace costs no comparison call), and walking the parser's node slabs by an index instead of reslicing them (0.5 % more copying the document, confirmed against an A/A pair).
The sixth to fifteenth rounds were measured on Linux (a 4-core x86-64 virtual machine) against the previous version rather than against libxslt, so the table above is unchanged; its XSLT 1.0 workloads moved by less than the noise.
An earlier version of this page put a third of the time into the operating system's memory calls. That came from the CPU profiler on macOS, which books kernel time to the wrong system call; measured directly, those calls take a few milliseconds. The garbage collector is the largest real share now. What remains is mostly the document and result trees themselves.
Same results
Both processors produce the same results. In two workloads the text differs in the last digits of sums: XPath 1.0 writes a number with as many digits as are needed to identify it exactly (17251.089999999997), libxslt rounds to 15 digits (17251.09). The benchmark compares numbers to 12 significant digits.
Running the benchmark
go run scripts/bench/main.go # -n runs, -records size of the inputIt builds the command-line tool from the checkout, generates the input, and prints this table for your machine. It needs xsltproc and xmllint, which macOS ships and Linux distributions package as xsltproc and libxml2-utils.