What is the difference between joining an array with shorthand or concatenation?

Consider the following array - strings -:

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

To combine its elements (to get "Hello" as a single line), we could:

reduce it:

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

Or join it:

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

Both will return the string "Hello" as output.

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

+4
source share
2 answers

There are two reasons why joineda better choice than reduce:

  • readability

    , reduce ? , . joined reduce.

  • joined String , reduce. , . reduce , , . joined , , . String. . String.joined.

, . , .

+6

iOS . MacOS , @Sulthan.


, reduce :

func benchmark(_ label: String, times: Int = 100000, _ f: () -> Void) {
    let start = CACurrentMediaTime()
    (0..<times).forEach { _ in f() }
    let end = CACurrentMediaTime()
    print("\(label) took \(end-start)")
}

let arrayStrings = ["H", "e", "l", "l", "o"]
benchmark("reduce", { _ = arrayStrings.reduce("", +) } )
benchmark("join", { _ = arrayStrings.joined() })

main iOS, :

reduce took 0.358474982960615
join took 0.582276367989834

, Release, :

reduce took 0.126910287013743
join took 0.0291724550188519

, reduce . , , , joined, , .

+2

Source: https://habr.com/ru/post/1693789/


All Articles