使用 mkString 与 foldRight 合并字符串列表 [英] Merging a list of Strings using mkString vs foldRight

查看:26
本文介绍了使用 mkString 与 foldRight 合并字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在 Scala 中尝试一些东西,试图习惯函数式编程并再次学习一门新语言(距离上次已经有一段时间了).

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).

现在给出一个字符串列表,如果我想将它们合并成一个长字符串(例如 "scala", "is", "fun" => "scalaisfun")我想出了一种方法要做到这一点,将执行一个 foldRight 并在相应的元素上应用连接.无可否认,另一种更简单的方法是调用 mkString.

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.

我在 github 上检查过,但无法真正找到相应功能的源代码(任何帮助将不胜感激),所以我不确定这些功能是如何实现的.在我的脑海中,我认为 mkString 更灵活,但感觉在某处的实现中可能有一个 foldRight .有什么道理吗?

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?

否则,scaladocs 提到 mkString 为每个相应的元素调用 toString.看到它们已经是字符串开始,这可能是 mkString 在这种特殊情况下的一个负面因素.对这两种方法在性能、简单性/优雅等方面的优缺点有何评论?

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?

推荐答案

简单的答案:使用 mkString.

someString.toString 返回相同的对象.

mkString 是用单个 StringBuilder 实现的,它只创建 1 个新字符串.使用 foldLeft,您将创建 N-1 个新字符串.

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

你可以在foldLeft中使用StringBuilder,它会和mkString一样快,但mkString更短:

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

这篇关于使用 mkString 与 foldRight 合并字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆