在Swift中对齐vs步幅

前端之家收集整理的这篇文章主要介绍了在Swift中对齐vs步幅前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Swift 4中,MemoryLayout结构告诉您类型的大小,跨度和对齐方式.

我理解大小和步幅,但不是真正的对齐.

是否有一个示例显示了什么是对齐,它与步幅有什么不同,何时它与步幅有不同的值,以及使用步幅但使用对齐是否正确?

我可以一直计算另一个吗?

这是一个简单的例子:
struct Foo {
    let a: Int16
    let b: Int8
}

print(MemoryLayout<Foo>.size)       // 3
print(MemoryLayout<Foo>.alignment)  // 2
print(MemoryLayout<Foo>.stride)     // 4

>结构的对齐是所有结构的最大对齐
字段,在这种情况下最大为2和1.
>结构的步幅是四舍五入到对齐,
这里3舍入到4的倍数.

步幅是内存中相同类型的连续实例(开始)之间的距离:

let array = [Foo(a: 1,b:2),Foo(a: 3,b: 4),Foo(a: 5,b: 6)]
array.withUnsafeBytes {
    print(Data($0) as NSData) // <01000234 03000474 0500066f>
    print($0.count) // 12
}

struct stride是struct alignment的倍数,因此
所有实例(以及所有实例字段)都已正确对齐.

细节可以在
Type Layout

Fragile Struct and Tuple Layout

Structs and tuples currently share the same layout algorithm,noted as the “Universal” layout algorithm in the compiler implementation. The algorithm is as follows:

  • Start with a size of 0 and an alignment of 1.
  • Iterate through the
    fields,in element order for tuples,or in var declaration order for
    structs. For each field:
    • Update size by rounding up to the alignment
      of the field,that is,increasing it to the least value greater or
      equal to size and evenly divisible by the alignment of the field.
    • Assign the offset of the field to the current value of size.
    • Update
      size by adding the size of the field.
    • Update alignment to the max of
      alignment and the alignment of the field.
  • The final size and alignment are the size and alignment of the aggregate. The stride of the type is the final size rounded up to alignment.
原文链接:https://www.f2er.com/swift/320014.html

猜你在找的Swift相关文章