代码源于这篇,https://blog.csdn.net/tencent_bugly/article/details/72145868,好文!👌
import UIKit
class MemoryViewController: UIViewController {
//对于c,内存区间分:
//Stack:
//Heap;
//代码区
//全局静态区
override func viewDidLoad() {
super.viewDidLoad()
//stack 每一格是8个字节(64位机器)
struct Point {
var x: Double //8 bytes
var y: Double //8 bytes
}
//类型大小
let size = MemoryLayout<Point>.size
print("size", size) // 16 bytes
//实例大小
let point1 = Point(x: 10, y: 20)
let point1Size = MemoryLayout<Point>.size(ofValue: point1)
print("point1Size", point1Size) //16 bytes
//heap
class PointClass {
var a: Double = 0.0
var b: Double = 0.0
init(aa: Double, bb: Double) {
self.a = aa
self.b = bb
}
}
//类型大小
let size2 = MemoryLayout<PointClass>.size
print("size2", size2) // 8 bytes
//实例大小
let point2 = PointClass(aa: 8, bb: 8)
let point2Size = MemoryLayout<PointClass>.size(ofValue: point2)
print("point2Size", point2Size)
//size 每个元素大小
//stride 每个元素实际占用的内存空间(内存对齐限制)
//stride-size为每个元素浪费的空间
//alignment 每个元素占用空间必须为k的倍数
//值类型
MemoryLayout<Int>.size //8
MemoryLayout<Int>.alignment //8
MemoryLayout<Int>.stride //8
MemoryLayout<String>.size //24
MemoryLayout<String>.alignment //8
MemoryLayout<String>.stride //24
class T { }
//引用类型 T
MemoryLayout<T>.size //8
MemoryLayout<T>.alignment //8
MemoryLayout<T>.stride //8
//指针类型
MemoryLayout<UnsafeMutablePointer<T>>.size //8
MemoryLayout<UnsafeMutablePointer<T>>.alignment //8
MemoryLayout<UnsafeMutablePointer<T>>.stride //8
MemoryLayout<UnsafeMutableBufferPointer<T>>.size //16
MemoryLayout<UnsafeMutableBufferPointer<T>>.alignment //16
MemoryLayout<UnsafeMutableBufferPointer<T>>.stride //16
//optional
struct PointOptional {
var x: Double? // 9 bytes
var y: Double // 8 bytes
}
print("Optional", MemoryLayout<Optional<Double>>.size) // 9 bytes
print("PointOptional", MemoryLayout<PointOptional>.size) // 24 bytes
enum Kind {
case wolf
case lion
case fox
case shark
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}