-
Copy On Write (COW)Swift 2023. 2. 23. 14:06
Copy On Write
원본과 복사본이 수정되기 전까지 같은 리소스를 공유하며, 원본이나 복사본이 수정될 때 복사가 이루어 지는 방식이다.
위 그림과 같이 Data와 CopyData는 수정작업이 있기 전까지는 같은 리소스를 공유하다가 수정작업이 이루어 질 때 복사하여 작업을 수행한다. Swift에서는 CollectionType에서 COW가 이루어진다.
코드로 살펴보기
func printAddress(of value: UnsafeRawPointer) { let address = Int(bitPattern: value) print(String(format:"%018p", address)) } unsafeBitCast(value, to: Int.self)
Heap영역에 데이터를 저장하는 CollectionType의 주소를 살펴보기 위해서는 위 두가지 방식으로 살펴볼 수 있다.
printAddress(of:)
함수를 이용해서 Array, String의 주소를 구할 수 있고,unsafeBitCast(_:,to:)
를 이용해서 Set, Dictionary의 주소를 구할 수 있다.
Set, Dictionary는 왜 UnsafeRawPointer로 안되는지, String은 왜 unsafeBitCast로 안되는지는 아직 모르겠습니다...Array
var array = [1,2,3] print("array = [1, 2, 3], address : ", terminator: "") printAddress(of: array) var copyArray = array print("copyArray = array") print("array address : ", terminator: "") printAddress(of: array) print("copyArray address : ", terminator: "") printAddress(of: copyArray) copyArray.append(9) print("copyArray append 9, copyArray address : ", terminator: "") printAddress(of: copyArray)
Set
var set: Set = [1,2,3] print("set = [1, 2, 3], address : ", terminator: "") var copySet = set print("copySet = set") print("set address : ", terminator: "") print(String(format:"%018p", unsafeBitCast(set, to: Int.self))) print("copySet address : ", terminator: "") print(String(format:"%018p", unsafeBitCast(copySet, to: Int.self))) copySet.insert(10) print("copySet insert 10, copySet address : ", terminator: "") print(String(format:"%018p", unsafeBitCast(copySet, to: Int.self)))
Dictionary
var dictionary = ["one": 1, "tow": 2, "three": 3] print("dictionary = [1, 2, 3], address : ", terminator: "") print(String(format:"%018p", unsafeBitCast(dictionary, to: Int.self))) var copyDictionary = dictionary print("copyDictionary = dictionary") print("dictionary address : ", terminator: "") print(String(format:"%018p", unsafeBitCast(dictionary, to: Int.self))) print("copyDictionary address : ", terminator: "") print(String(format:"%018p", unsafeBitCast(copyDictionary, to: Int.self))) copyDictionary["four"] = 4 print("copyDictionary append [\"four\": 4], copyDictionary address : ", terminator: "") print(String(format:"%018p", unsafeBitCast(copyDictionary, to: Int.self)))
String
var str = "1234567890123456" print("str = \(str), address : ", terminator: "") printAddress(of: str) var copyStr = str print("copyStr = str") print("str address : ", terminator: "") printAddress(of: str) print("copyStr address : ", terminator: "") printAddress(of: copyStr) copyStr += "write" print("copyStr append \"write\", copyStr address : ", terminator: "") printAddress(of: copyStr)
피드백 환영합니다!!