Rasto
Rasto

Reputation: 17744

How do I find how much memory is taken by a struct?

Simple question: Is there a way how to find out how much memory is taken by particular struct?

Ideally I would like it printed to console.


Edit: Krumelur came with simple solution using sizeof function.

Unfortunatelly it does not seems to work well with arrays. Following code

println("Size of int \(123) is: \(sizeofValue(123))")
println("Size of array \([0]) is: \(sizeofValue([0]))")
println("Size of array \([0, 1, 8, 20]) is: \(sizeofValue([0, 1, 8, 20]))")

Produces this output:

Size of int 123 is: 8
Size of array [0] is: 8
Size of array [0, 1, 8, 20] is: 8

So different sizes of arrays give same size what is surely incorrect (at least for my purpose).

Upvotes: 3

Views: 1873

Answers (3)

SimonL
SimonL

Reputation: 1838

As Declan McKenna pointed out, MemoryLayout.size is now a part of the standard library ("Foundation").

You use this in one of two ways: either you get the size of a type via <> bracket syntax, or of a value by calling it as a function:

var someInt: Int
let a = MemoryLayout.size(ofValue: someInt)
let b = MemoryLayout<Int>.size
/* a and b are equal */

Suppose you have an array arr of type T, you can get the allocated size as follows:

let size = arr.capacity * MemoryLayout<T>.size

Note that you should use arr.capacity, not arr.count. Capacity refers to how much memory has been reserved for the array, even if all the values haven't been written to.

Another thing to note is that memory allocations can be a bit tricky. If you allocate a large block of memory and never write to it, the operating system might not report the application as actually using that memory. The operating system might let you malloc some enormous block of memory that's a thousand times larger than your actual memory, but if you never actually write anything to it, it won't really get allocated.

The method described in this answer is for getting the hypothetical maximum amount allocated by the array.

Upvotes: 0

Declan McKenna
Declan McKenna

Reputation: 4870

This appears to be supported within the Swift standard library now.

Docs

MemoryLayout.size(ofValue: self)

Upvotes: 2

Krumelur
Krumelur

Reputation: 32497

The sizeof(T) operator is available in Swift. It returns the size taken up by the specified type or variable, just like in C.

Unlike C, however, there is no concept of a stack-allocated array (static array). An array is a pointer to an object, meaning that its size will always be a size of a pointer (this is the same as for heap-allocated arrays in C). To get the size of an array, you have to do something like

array.count * sizeof(Telement)

but even that is only true if Telement is not an object that allocates heap memory.

Upvotes: 4

Related Questions