我有一个XSLT,用于在浏览器中查看XML文件。 XSLT是天真的编写的,并且当前需要很长时间才能执行(几分钟)。
我的XML文件大小适中(〜1 MiB),并且同一文档的其他XSLT执行不同的处理的速度要快得多。所以我知道问题不是XML的大小,而是我的XSLT。
如何进行性能分析和优化XSLT?
(在浏览器中执行复杂的XSLT是一个坏主意吗?我应该改用XSLT应用程序端吗?)
最佳答案
您正在使用哪个XSLT引擎?如果您使用的是.NET引擎和Visual Studio,则可以使用集成到Visual Studio中的XSLT profiler,这非常有用。
其他出色的性能分析工具是Altova的XML Spy和Oxygen。
如果您要发布XSLT,则更容易告诉您可能出现的瓶颈。通常,请谨慎使用XPath表达式,例如'//',previous::*和following::*。其他一些规则和最佳做法:
- Avoid repeated use of
"//item"
.- Don't evaluate the same node-set more than once; save it in a variable.
- Avoid
<xsl:number>
if you can. For example, by using position().- Use
<xsl:key>
, for example to solve grouping problems.- Avoid complex patterns in template rules. Instead, use within the rule.
- Be careful when using the
preceding[-sibling]
orfollowing[-sibling]
axes. This often indicates an algorithm with n-squared performance.- Don't sort the same node-set more than once. If necessary, save it as a result tree fragment and access it using the
node-set()
extension function.- To output the text value of a simple
#PCDATA
element, use<xsl:value-of>
in preference to<xsl:apply-templates>
.(from http://www.dpawson.co.uk/xsl/sect4/N9883.html#d15756e150)
遵循这些规则通常会产生非常高效的XSLT,您可能根本不需要使用探查器。
关于您在浏览器中有关XSLT的问题:我不建议您这样做,因为首先您不是平台独立的(并非每个浏览器都可能支持它,或者某些浏览器可能只通过性能不佳的引擎支持它),其次您无法控制使用的引擎。
关于optimization - 如何分析和优化XSLT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/434976/