Swift MemoryLayout
MemoryLayout
public enum MemoryLayout<T> {
/// The contiguous memory footprint of `T`, in bytes.
///
/// A type's size does not include any dynamically allocated or out of line
/// storage. In particular, `MemoryLayout<T>.size`, when `T` is a class
/// type, is the same regardless of how many stored properties `T` has.
///
/// When allocating memory for multiple instances of `T` using an unsafe
/// pointer, use a multiple of the type's stride instead of its size.
public static var size: Int { get }
/// The number of bytes from the start of one instance of `T` to the start of
/// the next when stored in contiguous memory or in an `Array<T>`.
///
/// This is the same as the number of bytes moved when an `UnsafePointer<T>`
/// instance is incremented. `T` may have a lower minimal alignment that
/// trades runtime performance for space efficiency. This value is always
/// positive.
public static var stride: Int { get }
/// The default memory alignment of `T`, in bytes.
///
/// Use the `alignment` property for a type when allocating memory using an
/// unsafe pointer. This value is always positive.
public static var alignment: Int { get }
......
......
}
MemoryLayout 是个枚举 一种类型的内存布局,描述其大小、步长和对齐方式
值类型
struct Point {
let x: Double
let y: Double
let isFilled: Bool
}
//连续的内存占用量T,以字节为单位
MemoryLayout<Point>.size == 17
//存储在连续存储器或存储器中的一个实例的开始到下一个实例的开始的字节数
MemoryLayout<Point>.stride == 24
// 默认内存对齐方式T,以字节为单位
MemoryLayout<Point>.alignment == 8
引用性
class Point {
let x: Double
let y: Double
let isFilled: Bool
}
MemoryLayout<Point>.size == 8
MemoryLayout<Point>.stride == 8
MemoryLayout<Point>.alignment == 8
class是对象类型数据,使用MemoryLayout对class类型计算其内存结果实际上是对其class类型的引用指针进行操作