迅捷的表现:摆脱ContiguousArrayStorage deinit

时间:2015-02-21 00:39:25

标签: swift

我正在尝试优化Swift中的一些循环。

我有这门课,

class SphericalHarmonics {
    /** SphericalHarmonics Samples */
    struct SHSample {
        var sph:    Spherical
        var vec:    Vector3
        var coeff:  [Double]
    }

    let numBands    : UInt
    let numCoeffs   : UInt
    let numSamples  : UInt
    var samples     : [SHSample]
    var coeffs      : [Vector3]

并在init中初始化所有矩阵,然后循环访问10000个样本再次访问这些矩阵。

    let coefficients = [Double](count: Int(numCoeffs), repeatedValue: 0)
    let emptySample = SHSample(sph: Spherical(), vec: Vector3(), coeff: coefficients)
    samples = [SHSample](count: Int(self.numSamples), repeatedValue: emptySample)
    coeffs = [Vector3](count: Int(numCoeffs), repeatedValue: Vector3())
    // ...
    var i = 0 // array index
    for a in 0..<numSamplesSqrt {
        for b in 0..<numSamplesSqrt {
            // ...
            samples[i].sph = Spherical(r: 1.0, θ: Float(θ), φ: Float(φ))
            // convert spherical coords to unit vector
            samples[i].vec = samples[i].sph.ToVector3()
            // precompute all SH coefficients for this sample
            for l in 0..<Int(numBands) {
                for m in -l...l {
                    let ci = l * (l+1) + m // coefficient index
                    samples[i].coeff[ci] = SH(l: l,m: m,θ: θ,φ: φ)
                }
            }
            ++i

这里的第一个错误是从样本中读取[i]。分析会话显示,SHSample的Swift.Array._copyBuffer耗时2.2秒,而ContiguousArrayStorage._deallocating_deinit耗时2秒。我做了这个简单的改变并节省了4秒:)

            let sph = Spherical(r: 1.0, θ: Float(θ), φ: Float(φ))
            samples[i].sph = sph
            // convert spherical coords to unit vector
            samples[i].vec = sph.ToVector3()

然而,仍然有200ms的ContiguousArrayStorage._deallocating_deinit来自我正在访问samples [i] .coeff [ci]的最后一个内部循环。我真的不明白为什么需要调用deinit,因为数组已经创建了,我只是修改了他们的数据。

知道为什么吗?

(如果您想查看完整代码,请点击此处:https://github.com/endavid/Harmonikr/blob/master/Harmonikr/math/SphericalHarmonics.swift

0 个答案:

没有答案