optimization - Scala: Why does my tail call optimized code run slower? -


recently needed write functionality flatten data structure list(). wrote 2 functions:

  1. mutable , recursive, and
  2. immutable , tail optimized.

the immutable , tail optimized runs slower. why?

here code:

this recursive data structure flatten list[string]:

case class node[a](rootnode: a, subtree: list[node[a]]) 
  1. this mutable solution:

    def nodewalk(node: node[file]): list[string] = {    val ls = listbuffer[string]()    def recursenodes(node: node[file]): unit = {      node match {       case node(r, nil) => ls += r.getabsolutepath       case node(r, l) =>         ls += r.getabsolutepath         l.map { x => recursenodes(x) }     }   }   recursenodes(node)   ls.tolist } 
  2. this immutable , tail optimized solution

    import scala.util.control.tailcalls._ def nodewalk2(node: node[file]): list[string] = {   @annotation.tailrec   def nodewalker(node: node[file], acc: list[string]): list[string] = {     node match {       case node(r, list()) =>         r.getabsolutepath :: acc       case node(r, h :: t) =>         nodewalker(node(h.rootnode, (h.subtree ::: t)),                     r.getabsolutepath :: acc)     }   }    nodewalker(node, list()) } 

when did micro-benchmark, following results:

 type                items   time(ms) ------------------------------------ (mutable)           1978       5 (tail optimized)    1978       8  (mutable)           12619      12 (tail optimized)    12619      31  (mutable)           25203      12 (tail optimized)    25203      37  (mutable)           117876     24 (tail optimized)    117876     104  (mutable)           350000     82 (tail optimized)    350000     115  

is there reasonable explanation why tail optimized on jvm might slow? or there problem tail-call optimized code? suggestions improve code welcome.


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -