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

戏子无情 提交于 2019-11-28 20:51:01

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)

As far as I tested in the Playground, this function returns seemingly significant value:

func heapSize(_ obj: AnyObject) -> Int {
    return malloc_size(Unmanaged.passRetained(obj).toOpaque())
}

class MyClass {
    //no properites...
}
let myObj = MyClass()
print(heapSize(myObj)) //->16

class MyBiggerClass {
    var str: String?
    var i: Int = 0
}
let myBiggerObj = MyBiggerClass()
print(heapSize(myBiggerObj)) //->64

Seems the current Swift runtime uses malloc-compatible something to allocate memory in heap. (malloc gives some padding to fit the allocated size to power to 2, when allocating small chunks. So, the actually needed size for the instance may be smaller than the malloc_size.)

I haven't tested how far this would work, and undocumented behaviours just depending on the current implementation would change at any time in the future without any notifications.

But if you actually know that, this can be a good starting point for exploration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!