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 mkString
in this particular case. Any comments on the pros and cons of both methods, with respect to performance, simplicity/elegance etc?
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With