swift - 如果传递很多,Swift 中的结构会导致内存问题吗?

标签 swift memory-management struct

在 Swift 中,结构 是值类型。如果我有一个包含大量数据(假设)的结构,并将该结构传递给许多不同的函数,那么每次都会复制该结构吗?如果我同时调用它,那么内存消耗会很高吗?

最佳答案

理论上,如果您传递非常大的 struct 导致它们被复制,则可能存在内存问题。一些注意事项/观察结果:

  1. 在实践中,这很少成为问题,因为我们经常使用原生的“可扩展”Swift 属性,例如 StringArraySetDictionaryData 等,它们具有“写入时复制”(COW) 行为。这意味着如果您复制 struct,则不一定复制整个对象,而是它们在内部采用类似引用的行为来避免不必要的重复,同时仍保留值类型语义。但是,如果您对有问题的对象进行变异,则只会创建一个副本。

    这是两全其美的做法,您可以在其中享受值(value)语义(无意共享),而无需为这些特定类型重复不必要的数据。

    考虑:

    struct Foo {
        private var data = Data(repeating: 0, count: 8_000)
    
        mutating func update(at: Int, with value: UInt8) {
            data[at] = value
        }
    }
    

    此示例中的私有(private) Data 将采用 COW 行为,因此当您复制 Foo 的实例时,除非您变​​异,否则不会复制大负载

    最重要的是,您提出了一个假设性问题,而答案实际上取决于您的大型负载中涉及的类型。但对于许多原生 Swift 类型来说,这通常不是问题。

  2. 不过,让我们想象一下,您正在处理以下极端情况:(a) 您的组合有效负载很大; (b) 你的 struct 由不使用 COW 的类型组成(即,不是上述可扩展的 Swift 类型之一); (c) 您想继续享受值(value)语义(即不转移到具有意外共享风险的引用类型)。在 WWDC 2015 视频中 Building Better Apps with Value Types他们向我们展示了如何自己使用 COW 模式,避免不必要的复制,同时在对象发生变化时仍然强制执行真正的值类型行为。

    考虑:

    struct Foo {
        var value0 = 0.0
        var value1 = 0.0
        var value2 = 0.0
        ...
    }
    

    您可以将它们移动到私有(private)引用类型中:

    private class FooPayload {
        var value0 = 0.0
        var value1 = 0.0
        var value2 = 0.0
        ...
    }
    
    extension FooPayload: NSCopying {
        func copy(with zone: NSZone? = nil) -> Any {
            let object = FooPayload()
            object.value0 = value0
            ...
            return object
        }
    }
    

    然后您可以更改公开的值类型以使用此私有(private)引用类型,然后在任何变异方法中实现 COW 语义,例如:

    struct Foo {
        private var _payload: FooPayload
    
        init() {
            _payload = FooPayload()
        }
    
        mutating func updateSomeValue(to value: Double) {
            copyIfNeeded()
    
            _payload.value0 = value
        }
    
        private mutating func copyIfNeeded() {
            if !isKnownUniquelyReferenced(&_payload) {
                _payload = _payload.copy() as! FooPayload
            }
        }
    }
    

    copyIfNeeded 方法执行 COW 语义,使用 isKnownUniquelyReferenced 仅在有效负载未被唯一引用时才复制。

    这可能有点多,但它说明了如果您的大型有效负载尚未采用 COW,如何在您自己的值类型上实现 COW 模式。不过,我只建议这样做,如果 (a) 您的有效负载很大; (b) 您知道相关的有效负载属性尚不支持 COW,并且 (c) 您确定您确实需要这种行为。

  3. 如果您碰巧将协议(protocol)作为类型来处理,Swift 会自动在幕后使用 COW 本身,Swift 只会在值类型发生变化时制作大值类型的新副本。但是,如果您的多个实例未更改,它不会创建大型有效负载的副本。

    有关详细信息,请参阅 WWDC 2017 视频 What’s New in Swift: COW Existential Buffers :

    To represent a value of unknown type, the compiler uses a data structure that we call an existential container. Inside the existential container there's an in-line buffer to hold small values. We’re currently reassessing the size of that buffer, but for Swift 4 it remains the same 3 words that it's been in the past. If the value is too big to fit in the in-line buffer, then it’s allocated on the heap.

    And heap storage can be really expensive. That’s what caused the performance cliff that we just saw. So, what can we do about it? The answer is cow buffers, existential COW buffers...

    ... COW is an acronym for “copy on write”. You may have heard us talk about this before because it’s a key to high performance with value semantics. With Swift 4, if a value is too big to fit in the inline buffer, it's allocated on the heap along with a reference count. Multiple existential containers can share the same buffer as long as they’re only reading from it.

    And that avoids a lot of expensive heap allocation. The buffer only needs to be copied with a separate allocation if it’s modified while there are multiple references to it. And Swift now manages the complexity of that for you completely automatically.

    有关存在容器和 COW 的更多信息,请参阅 WWDC 2016 视频 Understanding Swift Performance .

关于swift - 如果传递很多,Swift 中的结构会导致内存问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54865785/

相关文章:

swift - Firebase:从实时数据库中检索数据作为 Int

发布请求后,IOS 出现错误,并带有附加符号 "\"

ios - 在起点画一个矩形,然后按照我的 Action 在 Swift 中结束手势

Java内存分配对齐

c++ - 我正在尝试计算 char 数组中的内容直到空终止,但每次编译时我得到的数字都大于我的数组

c - 使用 FILE 类型的结构时接收段错误 - C

c# - 当我有一个双倍结构时,为什么我的结构会出现意外的大小?

c - 将指向结构数组的指针设置为等于结构数组

ios - swift 3.0。向 UISearchBar 添加 View

Objective-C:在自动发布的 NSDictionary 中保留 NSDictionary