Size, Stride, Alignment

  • 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

Ref:​​​​​​Size, Stride, Alignment - Swift Unboxed

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值