Get the size (in bytes) of an object on the heap

前端 未结 2 520
萌比男神i
萌比男神i 2020-12-05 15:34

I\'m aware you can use MemoryLayout.size to get the size of a type T.

For example: MemoryLayout.size // 4

2条回答
  •  星月不相逢
    2020-12-05 16:11

    One option on Apple platforms, because Swift classes are currently built on top of Objective-C classes there, would be to use the Obj-C runtime function class_getInstanceSize, which gives you the size in bytes of an instance of the class, including any padding.

    // on a 64-bit machine (1 word == 8 bytes)...
    
    import Foundation
    
    class C {}
    print(class_getInstanceSize(C.self)) // 16 bytes metadata for empty class 
                                         // (isa ptr + ref count)
    
    class C1 {
        var i = 0
        var i1 = 0
        var b = false
    }
    
    print(class_getInstanceSize(C1.self)) // 40 bytes
    // (16 metadata + 24 ivars, 8 for i + 8 for i1 + 1 for b + 7 padding)
    

提交回复
热议问题