通过使用reduce或join合并数组有什么区别? [英] What is the difference between combining array by using reduce or joined?

查看:273
本文介绍了通过使用reduce或join合并数组有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下字符串数组:

Consider the following array -of strings-:

let arrayStrings = ["H", "e", "l", "l", "o"]

要合并其元素(以单个字符串形式获取"Hello"),我们可以:

For combining its elements (to get "Hello" as single String), we could:

减少 它:

let reducedString = arrayStrings.reduce("", { $0 + $1 }) // "Hello"

加入 :

let joinedString = arrayStrings.joined() // "Hello"

两者都将返回"Hello"字符串作为输出.

Both would return "Hello" String as output.

但是,确定该过程的最佳选择时应牢记的逻辑是什么?根据性能进行比较有什么区别?

However, what is the logic to keep in mind to determine what is the better choice for such a process? What is the difference when comparing based on the performance?

推荐答案

joinedreduce更好的选择有两个原因:

There are two reasons why joined is a better choice than reduce:

  1. 可读性

  1. Readability

如果要将多个字符串连接为一个字符串,为什么要使用reduce进行手动串联?如果您要执行的任务有特定功能,请使用它.阅读代码时,理解joinedreduce更容易.

If you want to join multiple strings into one string, why would you use reduce, with manual concatenation? If there is a specific function for the task you want to do, use it. When reading the code, it's easier to understand joined than reduce.

性能

joined可以比reduce更好地实现.它不是必须的,但是可以. reduce一次对一个元素进行操作,而无需了解其他元素,并且传递了许多临时变量. joined具有整个序列的知识,并且知道操作总是相同的,因此可以进行优化.它甚至可以使用String的内部结构.参见 String.joined实现.

joined for String can be implemented better than reduce. It does not have to be but it can. reduce operates on one element at a time, without knowledge about the other elements, with many temporary variables passed around. joined has the knowledge of the entire sequence and it knows that the operation is always the same, therefore it can optimize. It can even use the internal structure of String. See String.joined implementation.

总而言之,请始终使用更具体的实现. 请注意,上面的性能原因不太重要.

In summary, always use the more specific implementation. Note that the performance reason above is the less important one.

这篇关于通过使用reduce或join合并数组有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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