Poor performance of XML transform in Scala

瘦欲@ 提交于 2019-12-19 05:59:46

问题


I am trying to understand an XML transform performance problem:

Suppose I need to change the label of all elements with label a to label b.

val xml = ... // my input XML

val rule = new RewriteRule {
  override def transform(n: Node) = n match {
    case e: Elem if e.label == "a" => e.copy(label = "b")
    case other => other 
  }
}

new RuleTransformer(rule).apply(xml)

Unfortunately, when I run that code with an XML of ~30 elements it takes > 1 min (!) in a modern laptop.

For example:

scala> def gen(e: Elem, n: Int): Elem = 
       | if (n > 0) e.copy(child = e.child :+ gen(e, n-1)) else e
gen: (e: scala.xml.Elem, n: Int)scala.xml.Elem

scala> val xml = gen(<a/>, 25)
xml: scala.xml.Elem = <a><a><a><a><a><a><a> ...

scala> val rule = new RewriteRule {
       | override def transform(n : Node) = n match {
       | case e: Elem if e.label == "a" => e.copy(label = "b")
       | case other => other
       | }
       | }
rule: scala.xml.transform.RewriteRule = <function1>

scala> def transform(n: Node): Node = { 
       | val start = System.currentTimeMillis()
       | val r = new RuleTransformer(rule).apply(n)
       | println((System.currentTimeMillis() - start) / 1000)
       | r
       | }
transform: (n: scala.xml.Node)scala.xml.Node

scala> transform(xml)
99

Does such performance make sense ? Am I missing something ? How would you fix the code ?

来源:https://stackoverflow.com/questions/30330951/poor-performance-of-xml-transform-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!