optimization - Scala: Why does my tail call optimized code run slower? -
recently needed write functionality flatten data structure list(). wrote 2 functions:
- mutable , recursive, and
- 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]])
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 }
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
Post a Comment