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

I know that you can use MemoryLayout<T>.size to get a type size T

For example: MemoryLayout<Int32>.size // 4

However, for instances of the class (objects), MemoryLayout<T>.size returns the size of the object reference (8 bytes on 64-bit machines), and not the size of the actual objects on the heap.

 class ClassA { // Objects should be at least 8 bytes let x: Int64 = 0 } class ClassB {// Objects should be at least 16 bytes let x: Int64 = 0 let y: Int64 = 0 } MemoryLayout<ClassA>.size // 8 MemoryLayout<ClassB>.size // 8, as well :( 

How can I get the size of the objects themselves?

For those who are wondering, I don’t need it, I just study Swift and its interaction with C.

+6
source share
2 answers

One option on Apple platforms, since Swift classes are currently built on top of Objective-C classes , will use the Obj-C runtime function class_getInstanceSize , which gives you the size in bytes of the class instance, including any addition.

 // 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) 
+5
source

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.

+7
source

Source: https://habr.com/ru/post/1011827/


All Articles