As far as I tested in the Playground, this function returns an apparent 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
It seems that the current Swift runtime uses malloc
component something to allocate memory in a heap. ( malloc
gives some addition to the size of the allocated size equal to 2 when distributing small pieces. Thus, the actual required size for an instance may be smaller than malloc_size
.)
I have not tested how this will work, and undocumented behavior, depending on the current implementation, will change at any time in the future without any notifications .
But if you really know this, this may be a good starting point for research.
Ooper source share