swift MemoryLayout内存

在Xcode中点击MemoryLayout进去可以看到里面的解释说明以及例子。

MemoryLayout 内存布局,描述其大小、步幅和对齐方式。

@frozen public enum MemoryLayout<T> {

    //连续的内存占用量,以字节为单位
    public static var size: Int { get }

    //存储在连续存储器或存储器中的一个实例的开始到下一个实例的开始的字节数
    public static var stride: Int { get }
    
    //默认内存对齐方式,以字节为单位
    public static var alignment: Int { get }

    public static func size(ofValue value: T) -> Int

    public static func stride(ofValue value: T) -> Int

    public static func alignment(ofValue value: T) -> Int
    
    //返回内联存储属性在类型的内存中的偏移量
    //机器翻译:
    /* 您可以使用此方法查找可以添加到类型为' T '的指针的字节距离,以获得指向' key '引用的属性的指针。只有当给定的键指向内联的、可直接寻址的内存中' T '表示的存储时,偏移量才可用。*/
    public static func offset(of key: PartialKeyPath<T>) -> Int?


}

解释案例:

struct Point {
    let x:Double
    let y : Double
    let isFilled : Bool
}


 print(MemoryLayout<Point>.size)       //17
 print(MemoryLayout<Point>.stride)     //24
 print(MemoryLayout<Point>.alignment)  //8

在分配内存或计算内存中实例之间的距离时,总是使用类型的“stride”的倍数,而不是“size”的倍数。这个例子为' Point '的四个实例分配了未初始化的原始内存空间。

 let count = 4
 let pointPointer = UnsafeMutableRawPointer.allocate(byteCount: count*MemoryLayout<Point>.stride, alignment: MemoryLayout<Point>.alignment)

普通内存

var age = 10
MemoryLayout<Int>.size // 10
MemoryLayout<Int>.stride // 8
MemoryLayout<Int>.alignment // 8
MemoryLayout.size(ofValue: age) // 8 

​​​​​​​枚举内存

不会存入枚举变量的内存中:


  enum Session { // 这种是原始值(固定值) 不会存入枚举变量的内存中 原始值永远跟值绑定在一起,而且不允许在外部赋值
        case spring,summer,autumn,winter
    }

    print(MemoryLayout<Session>.size)        // 实际可能用到的空间大小  1
    print(MemoryLayout<Session>.stride)      // 分配占用的空间大小  1
    print(MemoryLayout<Session>.alignment)  // 对齐参数 1

关联值会被存入枚举变量的内存中:

  enum Person { //     这种是关联值 关联值会被存入枚举变量的内存中
        case attribute(Int,Int,Int,Int)
        case other
    }


   let person = Person.attribute(11, 11, 11, 11)  
   print(MemoryLayout.size(ofValue: person))     // 33
   print(MemoryLayout<Person>.size)              //实际可能用到的空间大小  33
   print(MemoryLayout<Person>.stride)           // 分配占用的空间大小  40
   print(MemoryLayout<Person>.alignment)        // 对齐参数 8
  enum Person { //     这种是关联值 关联值会被存入枚举变量的内存中
        case attribute(Int,Int,Bool,Bool)
        case other
    }



     let person = Person.attribute(11,11, true,true)
     print(MemoryLayout.size(ofValue: person))   //18
     print(MemoryLayout<Person>.size)            //18
     print(MemoryLayout<Person>.stride)          //24
     print(MemoryLayout<Person>.alignment)       //8

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值