Is complexity of scala.xml.RuleTransformer really exponential?

前端 未结 1 861
我寻月下人不归
我寻月下人不归 2021-01-13 10:13

This is a follow-up to one of my previous posts.

I tried to understand why the RuleTransformer performance is so poor. Now I believe that it is so slow because its c

相关标签:
1条回答
  • 2021-01-13 10:43

    This will be not a very rigours analysis, but the problem seems to be with the BasicTransformer's transform(Seq[Node]) method[1].

    The child transform method will be called twice for a node which is changed. Specifically in your example all the nodes will be called twice for this reason. And you are right in that each node at height h will be called 2^(h-1) times. Also note that at most one child of a node will be called twice because use of span and code, in the specific example all the child of the nodes will be called twice.

    Just to verify this wrote these code samples for modified RulesTransformer. ( I could have overriden RulesTransformer too. But anyway)

    // This is same as library RuleTransformer added with print statement
    class CopiedRuleTransformer(rules: RewriteRule*) extends BasicTransformer {
        override def transform(n: Node): Seq[Node] = {
            println(n)
            rules.foldLeft(super.transform(n)) { (res, rule) => rule transform res }
        }
    }
    

    My modified RuleTransformer

    class MyRuleTransformer(rules: RewriteRule*) extends BasicTransformer {
        override def transform(n: Node): Seq[Node] = {
            println(n)
            rules.foldLeft(super.transform(n)) { (res, rule) => rule transform res }
        }  
        override def transform(ns:Seq[Node]): Seq[Node] = {
            ns.flatMap(n => transform(n))
        } 
    }
    

    These codes are only for demonstrating purpose. You can call these as

    new CopiedRuleTransformer(rule).apply(node)
    

    or

    new MyRuleTransformer(rule).apply(node)
    

    [1] line : 34 https://github.com/scala/scala-xml/blob/master/src/main/scala/scala/xml/transform/BasicTransformer.scala

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