Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much storage does this Swift struct actually use?

Suppose I have the following struct –

struct MyStruct {
    var value1: UInt16
    var value2: UInt16
}

And I use this struct somewhere in my code like so -

var s = MyStruct(value1: UInt16(0), value2: UInt16(0))

I know that the struct will require 32-bits of storage for the two 16-bit integers –

What I am not certain about is whether swift is allocating two additional 64-bit pointers for each value in addition to one 64-bit pointer for the variable s.

Does this mean total storage requirement for the above code would result in the following?

MyStruct.value1     - 16-bits
MyStruct.value1 ptr - 64-bits
MyStruct.value2     - 16-bits
MyStruct.value2 ptr - 64-bits
s ptr               - 64-bits
–––––––––––––––––––––––––––––
Total               - 224-bits

Can someone please clarify?

like image 564
Randy Avatar asked Apr 13 '26 11:04

Randy


1 Answers

MyStruct is 4 bytes because sizeof(UInt16) is 2 bytes. To test this for any given type, use sizeof. sizeof return the memory in bytes.

let size = sizeof(MyStruct) //4

If you want to get the size of a given instance you can use sizeOfValue.

var s = MyStruct(value1: UInt16(0), value2: UInt16(0))
let sSize = sizeofValue(s) //4

I believe the size of the pointer will depend on the architecture/compiler which is 64-bits on most computers and many newer phones but older ones might be 32 bit.

I don't think there is a way to actually get a pointer to MyStruct.value1, correct me if i'm wrong (i'm trying &s.value1.

Pointers

Structs in Swift are created and passed around on the stack, that's why they have value semantics instead of reference semantics.

When a struct is created in a function, it is stored on the stack so it's memory is freed up at the end of the function. It's reference is just an offset from the Stack Pointer or Frame Pointer.

like image 196
Kevin Avatar answered Apr 18 '26 03:04

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!