为什么是“链接"?比“//link"快在 XPath 中? [英] Why is "link" faster than "//link" in XPath?

查看:18
本文介绍了为什么是“链接"?比“//link"快在 XPath 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此 XML,

library(xml2)

text = paste0(
  '<?xml version="1.0" encoding="UTF-8"?><items>',
  paste(rep(
  '<item type="greeting" id="9273938">
     <link type="1" id="139" value="Hi"/>
     <link type="1" id="142" value="Hello"/>
   </item>', 100),
        collapse = "\n"),
  '</items>')

x = xml_children(read_xml(text))

我可以使用 "link""//link" 选择所有链接节点并获得相同的结果 - 但速度却截然不同:

I can select all the link nodes by using "link" or "//link" and get the same result – but with very different speed:

bench::mark(
     link  = xml_find_all(x,   "link"),
  `//link` = xml_find_all(x, "//link"))[1:5]

# A tibble: 2 x 5
  expression      min   median `itr/sec` mem_alloc
  <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>
1 link          1.5ms   1.56ms     606.     10.6KB
2 //link       27.1ms  55.74ms      15.2   558.2KB

为什么差别这么大?

推荐答案

因为"link"只需要检查当前节点是否有名为link的子元素,而 "//link" 必须检查文档中的所有元素以查看哪些元素被命名为 link.

Because "link" only has to check if the current node has a child element named link, whereas "//link" has to check all elements in the document to see which are named link.

XPath 注释:

  • link" 只检查当前节点的直接子节点,因为默认轴是 child:: 轴.
  • "//link" 检查文档中的所有元素,因为 ///descendant-or-self::node() 的快捷方式/,所以 "//link"/descendant-or-self::node()/child::link 的缩写.
  • "link" only checks the immediate children of the current node because the default axis is the child:: axis.
  • "//link" checks all elements in the document because // is a shortcut for /descendant-or-self::node()/, so "//link" is short for /descendant-or-self::node()/child::link.

这篇关于为什么是“链接"?比“//link"快在 XPath 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆