This is a companion discussion topic for the original entry at https://www.raywenderlich.com/1940773-advanced-swift-unsafe-memory-access/lessons/2
This is a companion discussion topic for the original entry at https://www.raywenderlich.com/1940773-advanced-swift-unsafe-memory-access/lessons/2
Hi Ray,
In the Memory Sizing part, I took the SampleStruct example and changed the order of its properties in a new struct as follows:
struct SampleStruct {
var number: UInt32
var flag: Bool
}
MemoryLayout<SampleStruct>.size // returns 5
struct NewSampleStruct {
var flag: Bool
var number: UInt32
}
MemoryLayout<NewSampleStruct>.size // returns 8
I think I understood why this happens but I’d like to know if it has an incidence on my way of coding.
Does it mean that I have to take care of the properties order so as to get the smallest object size OR is it just virtual and both have the same size for the memory management even if the size provided by the MemoryLayout is different ?
Thanks.
That’s interesting. As I think you guessed, the alignment requirements for UInt32 are what is making it larger (though it has the same stride). In short, you do need to worry about it if you are trying to optimize for size.
Here is another example:
struct SampleStruct {
var number: UInt32
var flag: Bool
}
struct NewSampleStruct {
var flag: Bool
var number: UInt32
}
struct BigStruct {
var ss: SampleStruct
var b: Bool
}
struct NewBigStruct {
var nss: NewSampleStruct
var b: Bool
}
MemoryLayout<BigStruct>.size // 6
MemoryLayout<NewBigStruct>.size // 9
MemoryLayout<BigStruct>.stride // 8
MemoryLayout<NewBigStruct>.stride // 12
If you are interested in the gory details of type layout there is a nice document here: swift/TypeLayout.rst at main · apple/swift · GitHub
Thanks for your replies Ray.
This kind of memory allocation optimisation is really something new to me because I thought everything was perfectly handled by the system… I’ll pay attention to the way I order my properties now.
It’s an advanced course so I’d expect deep explanation of how it works. For example alignment property is not an easy thing and here it’s explained in one sentence which doesn’t say much about it. This video is mostly “run and see results, no explanation”. For better understanding I recommend to read this article: Size, Stride, Alignment - Swift Unboxed it is explained as it should be. 5 minutes is not enough to explain advanced topic like this.
Thanks for the link. Greg Heo stuff is great.