为什么这种for循环方法与地图方法相比是如此之慢?

时间:2017-10-02 23:48:20

标签: arrays swift performance for-loop map-function

我在Playground中测试了我的代码,但正如讨论所指出的那样,Playground是调试配置,一旦我将所有这些代码放在真正的应用程序中运行,它们就没有太大的区别。之前不知道这个调试/发布的事情。

与Swift性能相关的问题,我需要遍历图像的像素偏移,首先我是以这种方式尝试的。

func p1() -> [[Int]]{
    var offsets = [[Int]]()
    for row in 0..<height {
        var rowOffset = [Int]()
        for col in 0..<width {
            let offset = width * row + col
            rowOffset.append(offset)
        }
        offsets.append(rowOffset)
    }
    return offsets
}

但是它很慢,我搜索并发现了一些代码片段循环通过这种方式偏移:

func p2() -> [[Int]]{
    return (0..<height).map{ row in
        (0..<width).map { col in
            let offset = width * row + col
            return offset
        }
    }
}

所以我测试了如果我使用函数p1和p2来循环高度= 128和宽度= 128图像,p1比p2慢18倍,为什么p1比p2慢得多?另外我想知道还有其他更快的方法来完成这项任务吗?

1 个答案:

答案 0 :(得分:1)

map方法更快的最明显原因是因为map预先分配了数组容量(因为它知道结果数组中有多少元素)。您也可以通过调用阵列上的ary.reserveCapacity(n)在代码中执行此操作,例如

func p1() -> [[Int]]{
    var offsets = [[Int]]()
    offsets.reserveCapacity(height) // NEW LINE
    for row in 0..<height {
        var rowOffset = [Int]()
        rowOffset.reserveCapacity(width) // NEW LINE
        for col in 0..<width {
            let offset = width * row + col
            rowOffset.append(offset)
        }
        offsets.append(rowOffset)
    }
    return offsets
}