Wednesday, June 10, 2026
HomeiOS DevelopmentReminiscence structure in Swift - The.Swift.Dev.

Reminiscence structure in Swift – The.Swift.Dev.

[ad_1]

Reminiscence structure of worth sorts in Swift


Reminiscence is only a bunch of `1`s and `0`s, merely referred to as bits (binary digits). If we group the stream of bits into teams of 8, we are able to name this new unit byte (eight bit is a byte, e.g. binary 10010110 is hex 96). We are able to additionally visualize these bytes in a hexadecimal type (e.g. 96 A6 6D 74 B2 4C 4A 15 and many others). Now if we put these hexa representations into teams of 8, we’ll get a brand new unit referred to as phrase.

This 64bit reminiscence (a phrase represents 64bit) structure is the fundamental basis of our fashionable x64 CPU structure. Every phrase is related to a digital reminiscence handle which can also be represented by a (normally 64bit) hexadecimal quantity. Earlier than the x86-64 period the x32 ABI used 32bit lengthy addresses, with a most reminiscence limitation of 4GiB. Happily we use x64 these days. 💪


So how can we retailer our information sorts on this digital reminiscence handle area? Properly, lengthy story quick, we allocate simply the correct amount of area for every information sort and write the hex illustration of our values into the reminiscence. It is magic, offered by the working system and it simply works.


We may additionally begin speaking about reminiscence segmentation, paging, and different low stage stuff, however truthfully talking I actually do not know the way these issues work simply but. As I am digging deeper and deeper into low stage stuff like this I am studying lots about how computer systems work below the hood.


One vital factor is that I already know and I need to share with you. It’s all about reminiscence entry on varied architectures. For instance if a CPU’s bus width is 32bit meaning the CPU can solely learn 32bit phrases from the reminiscence below 1 learn cycle. Now if we merely write each object to the reminiscence with out correct information separation that may trigger some bother.


┌──────────────────────────┬──────┬───────────────────────────┐
│           ...            │  4b  │            ...            │
├──────────────────────────┴───┬──┴───────────────────────────┤
│            32 bytes          │            32 bytes          │
└──────────────────────────────┴──────────────────────────────┘


As you may see if our reminiscence information is misaligned, the primary 32bit learn cycle can solely learn the very first a part of our 4bit information object. It will take 2 learn cycles to get again our information from the given reminiscence area. That is very inefficient and likewise harmful, that is why many of the programs will not permit you unaligned entry and this system will merely crash. So how does our reminiscence structure appears like in Swift? Let’s take a fast take a look at our information sorts utilizing the built-in MemoryLayout enum sort.


print(MemoryLayout<Bool>.dimension)      
print(MemoryLayout<Bool>.stride)    
print(MemoryLayout<Bool>.alignment) 


print(MemoryLayout<Int>.dimension)       
print(MemoryLayout<Int>.stride)     
print(MemoryLayout<Int>.alignment)  


As you may see Swift shops a Bool worth utilizing 1 byte and (on 64bit programs) Int shall be saved utilizing 8 bytes. So, what the heck is the distinction between dimension, stride and alignment?

The alignment will inform you how a lot reminiscence is required (a number of of the alignment worth) to save lots of issues completely aligned on a reminiscence buffer. Measurement is the variety of bytes required to really retailer that sort. Stride will inform you in regards to the distance between two parts on the buffer. Don’t be concerned in case you do not perceive a phrase about these casual definitions, it will all make sense simply in a second.


struct Instance {
    let foo: Int  
    let bar: Bool 
}

print(MemoryLayout<Instance>.dimension)      
print(MemoryLayout<Instance>.stride)    
print(MemoryLayout<Instance>.alignment) 

When developing new information sorts, a struct in our case (courses work totally different), we are able to calculate the reminiscence structure properties, based mostly on the reminiscence structure attributes of the taking part variables.


┌─────────────────────────────────────┬─────────────────────────────────────┐
│         16 bytes stride (8x2)       │         16 bytes stride (8x2)       │
├──────────────────┬──────┬───────────┼──────────────────┬──────┬───────────┤
│       8 bytes    │  1b  │  7 bytes  │      8 bytes     │  1b  │  7 bytes  │
├──────────────────┴──────┼───────────┼──────────────────┴──────┼───────────┤
│   9 bytes dimension (8+1)    │  padding  │   9 bytes dimension (8+1)    │  padding  │
└─────────────────────────┴───────────┴─────────────────────────┴───────────┘


In Swift, easy sorts have the identical alignment worth dimension as their dimension. In the event you retailer commonplace Swift information sorts on a contiguous reminiscence buffer there is no padding wanted, so each stride shall be equal with the alignment for these sorts.

When working with compound sorts, such because the Instance struct is, the reminiscence alignment worth for that sort shall be chosen utilizing the utmost worth (8) of the properties alignments. Measurement would be the sum of the properties (8 + 1) and stride could be calculated by rounding up the dimensions to the subsequent the subsequent a number of of the alignment. Is that this true in each case? Properly, not precisely…


struct Instance {
    let bar: Bool 
    let foo: Int  
}

print(MemoryLayout<Instance>.dimension)      
print(MemoryLayout<Instance>.stride)    
print(MemoryLayout<Instance>.alignment) 


What the heck occurred right here? Why did the dimensions enhance? Measurement is difficult, as a result of if the padding is available in between the saved variables, then it will enhance the general dimension of our sort. You may’t begin with 1 byte then put 8 extra bytes subsequent to it, since you’d misalign the integer sort, so that you want 1 byte, then 7 bytes of padding and at last the 8 bypes to retailer the integer worth.


┌─────────────────────────────────────┬─────────────────────────────────────┐
│        16 bytes stride (8x2)        │        16 bytes stride (8x2)        │
├──────────────────┬───────────┬──────┼──────────────────┬───────────┬──────┤
│     8 bytes      │  7 bytes  │  1b  │     8 bytes      │  7 bytes  │  1b  │
└──────────────────┼───────────┼──────┴──────────────────┼───────────┼──────┘
                   │  padding  │                         │  padding  │       
┌──────────────────┴───────────┴──────┬──────────────────┴───────────┴──────┐
│       16 bytes dimension (1+7+8)         │       16 bytes dimension (1+7+8)         │
└─────────────────────────────────────┴─────────────────────────────────────┘


That is the primary purpose why the second instance struct has a barely elevated dimension worth. Be happy to create different sorts and follow by drawing the reminiscence structure for them, you may all the time examine in case you have been appropriate or not by printing the reminiscence structure at runtime utilizing Swift. 💡


This entire downside is actual properly defined on the [swift unboxed] weblog. I might additionally wish to advocate this text by Steven Curtis and there may be yet one more nice publish about Unsafe Swift: A street to reminiscence. These writings helped me lots to grasp reminiscence structure in Swift. 🙏


Reference sorts and reminiscence structure in Swift

I discussed earlier that courses behave fairly totally different that is as a result of they’re reference sorts. Let me change the Instance sort to a category and see what occurs with the reminiscence structure.


class Instance {
    let bar: Bool = true 
    let foo: Int = 0 
}

print(MemoryLayout<Instance>.dimension)      
print(MemoryLayout<Instance>.stride)    
print(MemoryLayout<Instance>.alignment) 


What, why? We have been speaking about reminiscence reserved within the stack, till now. The stack reminiscence is reserved for static reminiscence allocation and there is an different factor referred to as heap for dynamic reminiscence allocation. We may merely say, that worth sorts (struct, Int, Bool, Float, and many others.) reside within the stack and reference sorts (courses) are allotted within the heap, which isn’t 100% true. Swift is sensible sufficient to carry out further reminiscence optimizations, however for the sake of “simplicity” let’s simply cease right here.


You may ask the query: why is there a stack and a heap? The reply is that they’re fairly totally different. The stack could be quicker, as a result of reminiscence allocation occurs utilizing push / pop operations, however you may solely add or take away gadgets to / from it. The stack dimension can also be restricted, have you ever ever seen a stack overflow error? The heap permits random reminiscence allocations and you need to just be sure you additionally deallocate what you’ve got reserved. The opposite draw back is that the allocation course of has some overhead, however there is no such thing as a dimension limitation, besides the bodily quantity of RAM. The stack and the heap is kind of totally different, however they’re each extraordinarily helpful reminiscence storages. 👍


Again to the subject, how did we get 8 for each worth (dimension, stride, alignment) right here? We are able to calculate the true dimension (in bytes) of an object on the heap by utilizing the class_getInstanceSize technique. A category all the time has a 16 bytes of metadata (simply print the dimensions of an empty class utilizing the get occasion dimension technique) plus the calculated dimension for the occasion variables.


class Empty {}
print(class_getInstanceSize(Empty.self)) 

class Instance {
    let bar: Bool = true 
    let foo: Int = 0     
}
print(class_getInstanceSize(Instance.self)) 


The reminiscence structure of a category is all the time 8 byte, however the precise dimension that it will take from the heap will depend on the occasion variable sorts. The opposite 16 byte comes from the “is a” pointer and the reference rely. If you realize in regards to the Goal-C runtime a bit then this will sound acquainted, but when not, then don’t be concerned an excessive amount of about ISA pointers for now. We’ll discuss them subsequent time. 😅


Swift makes use of Computerized Reference Counting (ARC) to trace and handle your app’s reminiscence utilization. In many of the circumstances you do not have to fret about handbook reminiscence administration, due to ARC. You simply need to just be sure you do not create robust reference cycles between class cases. Happily these circumstances could be resolved simply with weak or unowned references. 🔄


class Writer {
    let title: String

    
    weak var publish: Put up?

    init(title: String) { self.title = title }
    deinit { print("Writer deinit") }
}

class Put up {
    let title: String
    
    
    var creator: Writer?

    init(title: String) { self.title = title }
    deinit { print("Put up deinit") }
}


var creator: Writer? = Writer(title: "John Doe")
var publish: Put up? = Put up(title: "Lorem ipsum dolor sit amet")

publish?.creator = creator
creator?.publish = publish

publish = nil
creator = nil



As you may see within the instance above if we do not use a weak reference then objects will reference one another strongly, this creates a reference cycle and so they will not be deallocated (deinit will not be referred to as in any respect) even in case you set particular person tips to nil. This can be a very primary instance, however the true query is when do I’ve to make use of weak, unowned or robust? 🤔


I do not wish to say “it relies upon”, so as an alternative, I might wish to level you into the fitting route. In the event you take a better take a look at the official documentation about Closures, you may see what captures values:

  • International features are closures which have a reputation and don’t seize any values.
  • Nested features are closures which have a reputation and may seize values from their enclosing perform.
  • Closure expressions are unnamed closures written in a light-weight syntax that may seize values from their surrounding context.

As you may see world (static features) do not increment reference counters. Nested features alternatively will seize values, similar factor applies to closure expressions and unnamed closures, however it’s kind of extra difficult. I might wish to advocate the next two articles to grasp extra about closures and capturing values:



Lengthy story quick, retain cycles suck, however in many of the circumstances you may keep away from them simply by utilizing simply the fitting key phrase. Below the hood, ARC does a terrific job, besides a number of edge circumstances when you need to break the cycle. Swift is a memory-safe programming language by design. The language ensures that each object shall be initialized earlier than you possibly can use them, and objects residing within the reminiscence that are not referenced anymore shall be deallocated mechanically. Array indices are additionally checked for out-of-bounds errors. This offers us an additional layer of security, besides in case you write unsafe Swift code… 🤓


Anyway, in a nutshell, that is how the reminiscence structure appears like within the Swift programming language.


[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments