Merging a list of Strings using mkString vs foldRight

孤人 提交于 2020-01-20 04:02:31

问题


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?


回答1:


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



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/16447681/merging-a-list-of-strings-using-mkstring-vs-foldright

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!