Merging a list of Strings using mkString vs foldRight

喜欢而已 提交于 2019-11-29 03:58:11

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

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