# Optimization

The XQuery expression `for $x at $p in EXPR return $p` is now rewritten as `1 to count(EXPR)`.

A filter expression that filters a constant sequence is now evaluated at compile time, provided the predicate does not use any variables and has no dependencies on the dynamic context other than the context item, position, and size.

"Loop-lifting" (extraction of subexpressions to prevent them being repeatedly evaluated within a loop) is now extended to XQuery `for` expressions that have a position variable.

Adjacent literal text nodes in the content of an element or document constructor are now merged at compile time. (These can arise as a result of early evaluation of expressions in the content sequence.)

The `AttributeValidator`, which checks whether required attributes are present and expands default values during schema validation, has been rewritten for efficiency, to do most of the work of setting up the necessary data structures at schema compile time rather than on a per-element basis at validation time. It also uses two different implementations of the main data structure to handle the typical case with a small number of attributes, and the more difficult but unusual case where large numbers of attributes are declared.

When an attribute has an enumeration type, space is saved on the instance tree by using references to the attribute value as held in the compiled schema, avoiding holding multiple copies of the same string.

In XSLT, multiple identical key definitions are now merged. These can arise when the same stylesheet module is imported several times in different places. Previously, this led to the construction of multiple indexes, whose results were merged at run-time.

The set of XPath expressions for which streamed evaluation is possible (using `saxon:stream()` or equivalent interfaces) has been slightly extended. It can now include expressions that return a union of elements and attributes; previously it was required to return exclusively elements, or exclusively attributes. It now allows multiple predicates (previously only a single predicate was allowed).

In XSLT, tail-call optimization is now performed for a call on `xsl:call-template` that appears within an `xsl:for-each` instruction, provided that it can be statically determined that the select expression of the `xsl:for-each` returns at most one item.

Next