gpt4 book ai didi

swift - 为什么存储子字符串可能会导致 Swift 中的内存泄漏?

转载 作者:行者123 更新时间:2023-11-28 06:10:16 25 4
gpt4 key购买 nike

关于 Apple 的文档 Substring , 是说:

Don’t store substrings longer than you need them to perform a specific operation. A substring holds a reference to the entire storage of the string it comes from, not just to the portion it presents, even when there is no other reference to the original string. Storing substrings may, therefore, prolong the lifetime of string data that is no longer otherwise accessible, which can appear to be memory leakage.

我很困惑String在Swift中是一个值类型,它是如何导致内存泄漏的?

最佳答案

Swift 数组、集合、字典和字符串具有值语义,但它们实际上是引用类型的写时复制包装器。换句话说,它们都是 classstruct 包装器。这允许以下内容在不制作副本的情况下工作:

let foo = "ABCDEFG"
let bar = foo

当您写入 String 时,它会使用标准库函数 isUn​​iquelyReferencedNonObjC(除非它被再次重命名)来检查是否有多个对支持对象的引用。如果是这样,它会在修改之前创建一个副本。

var foo = "ABCDEFG"
var bar = foo // no copy (yet)
bar += "HIJK" // backing object copied to keep foo and bar independent

当您使用子字符串(或数组切片)时,您会获得对整个支持对象的引用,而不仅仅是您想要的位。这意味着如果您有一个非常大的字符串并且您有一个只有 4 个字符的子字符串,只要该子字符串是事件的,您就会在内存中保存整个字符串后备缓冲区。这就是它警告您的泄漏。

关于swift - 为什么存储子字符串可能会导致 Swift 中的内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46921380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com