Contents
A brief introduction
- Value Types: Instance of
Structs
andenums
are passed byValue Types
, which has its own unique copy of data - Reference Types: Instances of
Classes
are passed byReference Types
, which can have several owners that share a copy
An example
Why did they have this difference
Allocation
Method dispatch
Static dispatch
- 能够在编译期确定执行方法的方式
- Value types use static dispatch by default
Dynamic dispatch
- 无法在编译期确定,只能在运行时去确定执行方法的分派方式
- Dynamic Dispatch is supported only by reference types
[图片上传失败...(image-9834c5-1667954505610)]
Increasing Performance by Reducing Dynamic Dispatch
我们知道Static dispatch快于Dynamic dispatch,如何在开发中去尽可能使用Static dispatch
- inheritance constraints: 使用final关键字去修饰Class,以此生成的Final class,使用Static dispatch
- access control: private关键字修饰,使得方法或属性只对当前类可见。编译器会对方法进行Static dispatch
- whole module optimization: 检查继承关系,对某些没有标记final的类通过计算,如果能在编译期确定执行的方法,则使用Static dispatch
When to use Value Types
This is especially helpful in multi-threaded environments where a different thread could alter your data.
Use a value type when you want copies to have an independent state, and the data will be used in code across multiple threads.
In Swift, Array, String, and Dictionary are all value types.
Mixed Types
Q&A
- Value Types是存储在heap还是stack
- 什么是Static dispatch和dynamic dispatch
- 初始化class/struct 能在memory graph看到吗
- Struct里面嵌套了class, 内存allocation会怎么样
- value types do not support inheritance?
- why value types can't store mutable data
refer
- Swift: Value Types vs Reference Types, and When to Use Each
- What is copy on write?
- 深入剖析Swift性能优化
- 理解Swift中struct和class在不同情况下性能的差异
- Swift 性能相关
- Swift性能优化(一)
- Swift性能优化
- Static vs Dynamic Dispatch in Swift: A decisive choice
- A Deep Dive Into Method Dispatches in Swift
- Increasing Performance by Reducing Dynamic Dispatch
- Reference vs. Value Types in Swift
- Difference between value type and a reference type in iOS swift?
- Swift Method Dispatch