Suppose there are two arrays, one with n number of Class
elements and one with n number of Struct
elements. Which will consume more memory? Also what happens when we start manipulating the arrays. Below is what I tried.
class C {
var a = ""
}
struct S {
var a = ""
}
func sizeOf<T>(_ value: T) {
print(MemoryLayout.size(ofValue: value))
}
let classVar = C()
let structVar = S()
let arrayClass = [classVar, classVar, classVar]
var arrayStruct = [structVar, structVar, structVar]
sizeOf(classVar)
sizeOf(structVar)
sizeOf(arrayClass)
sizeOf(arrayStruct)
var newStruct = structVar
newStruct.a = "Value changed"
sizeOf(structVar)
arrayStruct.append(newStruct)
sizeOf(arrayStruct)
Output
8
16
8
8
16
8
Why is struct size greater than class and also why are both the array of the same size? Is it because array itself is a struct? Can someone provide with detailed explanation?