Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging a list of Strings using mkString vs foldRight

I am currently trying out things in Scala, trying to get accustomed to functional programming as well as leaning a new language again (it's been a while since last time).

Now given a list of strings if I want to merge them into one long string (e.g. "scala", "is", "fun" => "scalaisfun") I figured one way to do it would be to do a foldRight and apply concatenation on the respective elements. Another way, admittedly much simpler, is to call mkString.

I checked on github but couldn't really find the source code for the respective functions (any help on that would be appreciated), so I am not sure how the functions are implemented. From the top of my head, I think the mkString is more flexible but it feels that there might be a foldRight in the implementation somewhere. Is there any truth to it?

Otherwise the scaladocs mention that mkString calls on toString for each respective element. Seeing that they are already strings to start with, that could be one negative point for mkStringin this particular case. Any comments on the pros and cons of both methods, with respect to performance, simplicity/elegance etc?

like image 832
posdef Avatar asked May 08 '13 18:05

posdef


3 Answers

Simple answer: use mkString.

someString.toString returns the same object.

mkString is implemented with a single StringBuilder and it creates only 1 new string. With foldLeft you'll create N-1 new strings.

You could use StringBuilder in foldLeft, it will be as fast as mkString, but mkString is shorter:

strings.foldLeft(new StringBuilder){ (sb, s) => sb append s }.toString
strings.mkString // same result, at least the same speed
like image 53
senia Avatar answered Nov 11 '22 11:11

senia


Don't use foldRight unless you really need it, as it will overflow your stack for large collections (for some types of collections). foldLeft or fold will work (does not store intermediate data on the stack), but will be slower and more awkward than mkString. If the list is nonempty, reduce and reduceLeft will also work.

like image 44
Rex Kerr Avatar answered Nov 11 '22 10:11

Rex Kerr


Im memory serves, mkString uses a StringBuilder to build the String which is efficient. You could accomplish the same thing using a Scala StringBuilder as the accumulator to foldRight, but why bother if mkString can already do all that good stuff for you. Plus mkString gives you the added benefit of also including an optional delimiter. You could do that in foldRight but it's already done for you with mkString

like image 3
cmbaxter Avatar answered Nov 11 '22 11:11

cmbaxter