swift MemoryLayout for class and struct

197 Views Asked by At

I am investigating MemoryLayout and I came across this:

struct A {
    var name:String
}
class B {
    var name:String

    init(name: String) {
        self.name = name
    }
}
let a = A(name: "a")
let sizeA = MemoryLayout.size(ofValue: a)
print("struct size: " + "\(sizeA)")    // 16
   
let b = B(name: "B")
let sizeB = MemoryLayout.size(ofValue: b)
print("class size: " + "\(sizeB)").   // 8

Can you please explain to me why the size is different? Thanks

1

There are 1 best solutions below

0
Timmy On

When using size(ofValue:) for a class, the returned value is the size of the pointer of that class. However, when dealing with a struct it returns the size of that instance hence the diffrence.

More info here: When is my struct too large?