- Size is the number of bytes to read from the pointer to reach all the data.
- Stride is the number of bytes to advance to reach the next item in the buffer.
- Alignment is the the “evenly divisible by” number that each instance needs to be at. If you’re allocating memory to copy data into, you need to specify the correct alignment (e.g.
allocate(byteCount: 100, alignment: 4)).
这里的instance理解为struct里的 每个member的对齐

MemoryLayout<Int>.size
// returns 8 on my pc
MemoryLayout<Int32>.size
// returns 4
MemoryLayout<Int32>.alignment
// returns 4
MemoryLayout<Int32>.stride
// returns 4
注意bool的对齐
struct CertifiedPuppy1 {
let age: Int
let isTrained: Bool
let isCertified: Bool
}
MemoryLayout<CertifiedPuppy1>.size // 10
MemoryLayout<CertifiedPuppy1>.stride // 16
MemoryLayout<CertifiedPuppy1>.alignment // 8
struct CertifiedPuppy2 {
let isTrained: Bool
let age: Int
let isCertified: Bool
}
MemoryLayout<CertifiedPuppy2>.size // 17
MemoryLayout<CertifiedPuppy2>.stride // 24
MemoryLayout<CertifiedPuppy2>.alignment // 8
本文探讨了Swift中的Size、Stride和Alignment概念,通过实例展示了如何影响内存分配和struct成员对齐。重点讲解了`CertifiedPuppy`结构体中不同字段排列对内存布局的影响,并介绍了在内存优化中的关键参数。
947

被折叠的 条评论
为什么被折叠?



