Swift performance: map() and reduce() vs for loops

后端 未结 3 1405
感情败类
感情败类 2020-12-12 18:14

I\'m writing some performance-critical code in Swift. After implementing all the optimizations I could think of, and profiling the application in Instruments, I came to rea

3条回答
  •  感动是毒
    2020-12-12 18:48

    I cannot say much about your first test (map() vs append() in a loop) but I can confirm your results. The append loop becomes even faster if you add

    output.reserveCapacity(array.count)
    

    after the array creation. It seems that Apple can improve things here and you might file a bug report.

    In

    for _ in 0..<100_000 {
        var sum: Float = 0
        for element in array {
            sum += element
        }
    }
    

    the compiler (probably) removes the entire loop because the computed results are not used at all. I can only speculate why a similar optimization does not happen in

    for _ in 0..<100_000 {
        let sum = array.reduce(0, combine: {$0 + $1})
    }
    

    but it would more difficult to decide if calling reduce() with the closure has any side-effects or not.

    If the test code is changed slightly to calculate and print a total sum

    do {
        var total = Float(0.0)
        let start = NSDate()
        for _ in 0..<100_000 {
            total += array.reduce(0, combine: {$0 + $1})
        }
        let elapsed = NSDate().timeIntervalSinceDate(start)
        print("sum with reduce:", elapsed)
        print(total)
    }
    
    do {
        var total = Float(0.0)
        let start = NSDate()
        for _ in 0..<100_000 {
            var sum = Float(0.0)
            for element in array {
                sum += element
            }
            total += sum
        }
        let elapsed = NSDate().timeIntervalSinceDate(start)
        print("sum with loop:", elapsed)
        print(total)
    }
    

    then both variants take about 10 seconds in my test.

提交回复
热议问题