Performance of XPath vs DOM

前端 未结 3 739
伪装坚强ぢ
伪装坚强ぢ 2020-12-29 07:00

Would anyone enlighten me some comprehensive performance comparison between XPath and DOM in different scenarios? I\'ve read some questions in SO like xPath vs DOM API, whic

相关标签:
3条回答
  • 2020-12-29 07:40

    This page has a section where you can run tests to compare the two and see the results in different browsers. For instance, for Chrome, xpath is 100% slower than getElementById.

    See getElementById vs QuerySelector for more information.

    0 讨论(0)
  • 2020-12-29 07:54

    XPath and DOM are both specifications, not implementations. You can't ask questions about the performance of a spec, only about specific implementations. There's at least a ten-to-one difference between a fast XPath engine and a slow one: and they may be optimized for different things, e.g. some spend a lot of time optimizing a query on the assumption it will be executed multiple times, which might be the wrong thing to do for single-shot execution. The one thing one can say is that the performance of XPath depends more on the engine you are using, and the performance of DOM depends more on the competence of the application programmer, because it's a lower-level interface. Of course all programmers consider themselves to be much better than average...

    0 讨论(0)
  • 2020-12-29 07:56

    I agree with Michael that it may depends on implementation, but I would generally say that DOM is faster. The reason is because there is no way that I see you can optimize the parsed document to make XPath faster.

    If you're traversing HTML and not XML, specialized parser is able to index all the ids and classes in the document. This will make getElementById and getElementsByClass much faster.

    With XPath, there's only one way to find the element of that id...by traversing, either top down or bottom up. You may be able to memoize repeated queries (or partial queries), but I don't see any other optimization that can be done.

    0 讨论(0)
提交回复
热议问题