Way to tell how much an object is in Memory ?

At the moment just wanting to compare memory space difference between an AVAsset or String, but this would be a handy to tell for most objects anyway.


Any ideas ?

Replies

You should find your answer here:


h ttps://en.swifter.tips/sizeof-sizeofValue/

Apparently this only points to the pointer not how much an instance is in memory.


(Xcode 10, Swift 4.2) I tried

"malloc_size(class_getInstanceSize(object))" but shows error "Cannot convert value of type 'object class' to expected argument type 'AnyClass?' (aka 'Optional<AnyObject.Type>')"

I tried

"malloc_size(class_getInstanceSize(object))" but shows error "Cannot convert value of type 'object class' to expected argument type 'AnyClass?' (aka 'Optional<AnyObject.Type>')"


Seems you are mixing up two different ways in a wrong manner.


If you want to use `malloc_size`, you need to pass `UnsafeRawPointer!`.


malloc_size(Unmanaged.passRetained(object).toOpaque())


If you prefer `class_getInstanceSize`, you need to pass the class of an instance, not the instance itself.


class_getInstanceSize(type(of: object))


Example:

class AClass {
    var str: String?
    var i: Int = 0
}
let object = AClass()
print(malloc_size(Unmanaged.passRetained(object).toOpaque())) //->48
print(class_getInstanceSize(type(of: object))) //->40


As you have noticed, the two return different numbers in some cases. `malloc_size` returns actually allocated heap size (not including the memory size needed for managing heap), and `class_getInstanceSize` returns actual memory size calculated by compiler.

The size of variable `object` (8-bytes in 64-bit platform) is not included in neither cases.


Detecting memory space is difficult and can be ambiguous. The number 48 or 40 in the example does not contain the memory size allocated for `str`. When asign a long String to `str`, some amount of memory is allocated somewhere else in heap.

What makes you think the "size" you're asking for can be meaningfully determined?


— In the case of a String, as with a lot of objects, you have no reason to assume that the backing storage is contained in a single malloc'ed block. The way storage is managed may frequently vary between instances of the same class.


— In the case of AVAsset, as with a lot of objects, there might be private properties that refer to another object. For example, an AVAsset may contain internal references to one or more NSURL objects. Would you want to account for those as part of the AVAsset's memory budget? If so, how? If not, why not? How would you account for memory that is shared between multiple objects?


— In Swift, it's possible for an object (an instance of a reference type) to be allocated on the stack if small. What do you think malloc_size is going to tell you about that case? You can only validly ask for the malloc size if the memory was originally a malloc block, and you've got no justification for assuming that in the general case.