gpt4 book ai didi

arrays - Swift 如何实现 Array 的写时复制行为?

转载 作者:可可西里 更新时间:2023-11-01 01:36:44 28 4
gpt4 key购买 nike

看完build better apps with value type .在他们制作的photoshop示例中,他们说

the only thing that gets copied in the two instances of that diagram are the tiles that contain the person's shirt. So even though I have two distinct documents, the old state and the new state, the only new data that I have had to consume as a result of that is the tiles contained in this person's shirt.

所以我开始想知道这两个数组在内存中会是什么样子。所以我做了一个小实验。

struct Test {
var i: Int
var j: Int
}

var valueArray = [Test(i: 1, j: 9), Test(i: 2, j: 7)]
var valueArray2 = valueArray

当我打印 valueArray 和 valueArray2 的地址时,它们是不一样的。
“也许他们通过在数组中存储指针来实现它?”
但是当我使用 lldb 打印内存内容时,它们实际上只是 4 Int (1,9,2,7)。
所以我很困惑,我什至还没有更改数组。他们似乎复制了整个数组?那我哪里误会了?
我用来打印结构地址的函数是使用@nschum 在this question 中提供的方法。 .

func address(o: UnsafePointer<Void>) {
let addr = unsafeBitCast(o, Int.self)
print(NSString(format: "%p", addr))
}

这不是 this question 的重复问题.我问的是语言羽毛,另一个是关于编程技巧。

最佳答案

好吧,我做了很多实验,终于弄明白了。

  1. 我们可以使用 & 获取数组地址,因为一旦我们这样做,Swift 将复制数组以更好地与 C 交互,使用 & 获取对象的相邻地址数组并改为进行数学运算。 或者使用lldb指令frame variable -L
  2. 一旦数组的任何值元素发生变化,就会复制整个数组。
  3. Array 的实际值元素在堆上分配。
  4. Swift 也对元素为class 的Array 做了很多优化。
  5. Swift 很棒。

我实际上写了my first blog为此。

关于arrays - Swift 如何实现 Array 的写时复制行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36490992/

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