Swift 函数派发方式

Swift 支持四种函数派发方式,分别是:

  • inline 内敛 (最快)
  • 静态派发
  • 虚表派发
  • OC消息派发(最慢)

下面分别对值类型协议介绍它们的派发方式。

1. 值类型的函数派发:

这里先给出结论,方便阅读后续的验证:

  1. 值类型只支持静态派发。包括static方法,init方法、内部方法、通过extension扩展值类型实现的方法,同时也包括调用协议定义的方法和通过协议extension扩展实现的方法
  2. 协议实例调用extension的方法是静态派发, 调用协议中定义的方法是虚表派发。
    2.1 协议中定义的方法本身没有实现,是遵循协议的值类型或类实现的,协议会对遵循协议的所有值类型或类分别创建虚表。
    2.2 具体调用流程为:协议类型实例调用方法 --> 编译器根据实例对应的真实类型metadata, 在协议找到对应虚表 --> 虚表首地址+offset得到真实的函数地址 --> 汇编bl调用函数
  • 定义一个protocol Vehiclestruct Car: Vehicle, 让Car遵循Vehicle协议,通过断点汇编的方式验证每一种函数调用方式的派发方式
protocol Vehicle {
    var brand: String { get } 
    var color: String { get }
    func otherDescription() -> String
}

extension Vehicle {
    func show() {
        print("品牌:\(brand); 颜色:\(color); \(otherDescription())")
    }
}

struct Car: Vehicle {
    static func getMaxLenght() -> String {
        return "6M"
    }
    let brand: String
    let color: String
    let passengers: Int
    
    init(brand: String, color: String, passengers: Int) {
        self.brand = brand
        self.color = color
        self.passengers = passengers
    }
    
    func run() {
        print("Car run...")
    }
    
    func otherDescription() -> String {
        "限乘:\(passengers)人"
    }
}

extension Car {
    func performance() {
        print("high performance")
    }
}

Car.getMaxLenght() // 1. 值类型调用`static`修饰的方法, 【静态派发】
let bmw = Car(brand: "宝马", color: "蓝色", passengers: 5)  // 2. 值类型调用初始化方法,【静态派发】
bmw.run() // 3. 值类型调用内部定义的方法, 【静态派发】
bmw.performance() // 4. 值类型调用拓展中的方法, 【静态派发】
bmw.otherDescription() // 5. 值类型调用协议定义的方法, 【静态派发】
bmw.show() // 6. 值类型调用协议拓展中的方法, 【静态派发】

let vehicle: Vehicle = bmw // `vehicle `为Vehicle协议类型
vehicle.show() // 7. 通过协议调用协议拓展中的方法, 【静态派发】
vehicle.otherDescription() // 8. 通过协议调用协议定义的方法, 【虚表派发】
  1. 值类型调用static修饰的函数Car.getMaxLenght(), 静态派发方式
    值类型调用`static`修饰的函数`Car.getMaxLenght()`
  2. 值类型调用init初始化方法, let bmw = Car.init(), 静态派发方式
    值类型调用`init`初始化方法, `let bmw = Car.init()`
  3. 值类型调用内部定义的方法bmw.run(), 静态派发方式
    值类型调用内部定义的方法`bmw.run()`
  4. 值类型调用拓展中的方法bmw.performance(), 静态派发方式
    值类型调用拓展中的方法`bmw.performance()`
  5. 值类型调用协议定义的方法bmw.otherDescription(), 静态派发方式
    值类型调用协议定义的方法`bmw.otherDescription()`
  6. 值类型调用协议拓展中的方法bmw.show(), 静态派发方式
    值类型调用协议拓展中的方法`bmw.show()`
  7. 通过协议调用协议拓展中的方法vehicle.show(), 静态派发方式
    通过协议调用协议拓展中的方法`vehicle.show()`
  8. 通过协议调用协议定义的方法vehicle.otherDescription(), 虚表派发方式
    这里不能直接在断点汇编中判断出派发方式,但是可以分析调用的汇编
    先删除其他的调用,只断点vehicle.otherDescription()这行代码
    删除其他调用.png

    编译运行,查看汇编,有几个关键步骤):
    step1: type metadata for Car : 拿到结构体Car的metadata
    step2: protocol witness table for Car : Vehicle: 找到协议Vehicle为结构体Car分配的虚表
    step3: ldr x8, [x1, #0x18]: 虚表首地址+0x18, 得到结构体otherDescription函数的地址
    step4: protocol witness for Vehicle.otherDescription() -> String in conformance Car : Vehicle at <compiler-generated> : 这个虚表是编译器为值类型Car生成的,并与协议Vehicle有映射关系
    step5: blr x8: 执行otherDescription函数
    通过协议调用协议定义的方法的关键步骤

通过上面的汇编和寄存器值,可以大胆猜测:

  • 对于所有实现协议方法的值类型或类,编译器都会生成一个协议与值类型或类对应的虚表,通过协议类型调用方法都在这个虚标中去查找。
  • 具体调用流程为:协议类型实例调用方法 --> 编译器根据实例对应的真实类型metadata, 在协议找到对应虚表 --> 虚表首地址+offset得到真实的函数地址 --> 汇编bl调用函数

SIL验证协议虚表派发

  • 将上面的代码简化,协议只定义一个方法,让值类型和类都遵循协议

protocol Vehicle {
    func type() -> String
}

struct Car: Vehicle {
    func type() -> String {
        "小轿车"
    }
}

let car = Car()
let vehicleForCar: Vehicle = car
  • 然后生成对应的SIL文件

生成SIL的命令为: swiftc -emit-silgen main.swift | xcrun swift-demangle > ./main.sil
备注:由于文件内容太多,下面的SIL删除了一些内容, 删除的部分用......代替

......
// main
sil [ossa] @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 {
.....
  %9 = global_addr @main.vehicleForCar : main.Vehicle : $*Vehicle // users: %13, %11
  %10 = load [trivial] %3 : $*Car                 // user: %12
  %11 = init_existential_addr %9 : $*Vehicle, $Car // user: %12
  store %10 to [trivial] %11 : $*Car              // id: %12

  //  open_existential_addr 表示
  %13 = open_existential_addr immutable_access %9 : $*Vehicle to $*@opened("66F9CFF0-7166-11EC-89C2-1A18502C3718") Vehicle // users: %15, %15, %14
  %14 = witness_method $@opened("66F9CFF0-7166-11EC-89C2-1A18502C3718") Vehicle, #Vehicle.type : <Self where Self : Vehicle> (Self) -> () -> String, %13 : $*@opened("66F9CFF0-7166-11EC-89C2-1A18502C3718") Vehicle : $@convention(witness_method: Vehicle) <τ_0_0 where τ_0_0 : Vehicle> (@in_guaranteed τ_0_0) -> @owned String // type-defs: %13; user: %15
  %15 = apply %14<@opened("66F9CFF0-7166-11EC-89C2-1A18502C3718") Vehicle>(%13) : $@convention(witness_method: Vehicle) <τ_0_0 where τ_0_0 : Vehicle> (@in_guaranteed τ_0_0) -> @owned String 
.....
} // end sil function 'main'
......

上面的SIL中有几个关键命令:
open_existential_addr :找到Vehicle与Car关联的虚表地址
witness_method: 找到虚表对应的方法,这个方法会对Car实现的func type() -> String包装一次
apply: 执行witness_method找到的方法。

// protocol witness for Vehicle.type() in conformance Car
sil private [transparent] [thunk] [ossa] @protocol witness for main.Vehicle.type() -> Swift.String in conformance main.Car : main.Vehicle in main : $@convention(witness_method: Vehicle) (@in_guaranteed Car) -> @owned String {
// %0                                             // user: %1
bb0(%0 : $*Car):
  %1 = load [trivial] %0 : $*Car                  // user: %3
  // function_ref Car.type()
  %2 = function_ref @main.Car.type() -> Swift.String : $@convention(method) (Car) -> @owned String // user: %3
  %3 = apply %2(%1) : $@convention(method) (Car) -> @owned String // user: %4
  return %3 : $String                             // id: %4
} // end sil function 'protocol witness for main.Vehicle.type() -> Swift.String in conformance main.Car : main.Vehicle in main'

上面的SIL对Car实现的func type() -> String包装一次,猜测是Car原来实现的方法只支持静态派发,所以自动生成一个函数用于表派发

sil_witness_table hidden Car: Vehicle module main {
  method #Vehicle.type: <Self where Self : Vehicle> (Self) -> () -> String : @protocol witness for main.Vehicle.type() -> Swift.String in conformance main.Car : main.Vehicle in main   // protocol witness for Vehicle.type() in conformance Car
}

上面的SIL就是协议Vehicle为结构体Car生成的虚表。

  • 如果协议Vehicle分别被值类型和类遵循,SIL是什么效果呢?

  • 重新修改源码
protocol Vehicle {
    func type() -> String
}

struct Car: Vehicle {
    func type() -> String {
        "小轿车"
    }
}

enum Truck: Vehicle {
    func type() -> String {
        "货车"
    }
}

final class Bicycle: Vehicle {
    func type() -> String {
        "货车"
    }
}
  • 重新生成SIL, 3个虚表, 包装了3个方法
// protocol witness for Vehicle.type() in conformance Car
sil private [transparent] [thunk] [ossa] @protocol witness for main.Vehicle.type() -> Swift.String in conformance main.Car : main.Vehicle in main : $@convention(witness_method: Vehicle) (@in_guaranteed Car) -> @owned String {
// %0                                             // user: %1
bb0(%0 : $*Car):
  ...
}

// protocol witness for Vehicle.type() in conformance Truck
sil private [transparent] [thunk] [ossa] @protocol witness for main.Vehicle.type() -> Swift.String in conformance main.Truck : main.Vehicle in main : $@convention(witness_method: Vehicle) (@in_guaranteed Truck) -> @owned String {
// %0                                             // user: %1
bb0(%0 : $*Truck):
  ...
}

// protocol witness for Vehicle.type() in conformance Bicycle
sil private [transparent] [thunk] [ossa] @protocol witness for main.Vehicle.type() -> Swift.String in conformance main.Bicycle : main.Vehicle in main : $@convention(witness_method: Vehicle) (@in_guaranteed Bicycle) -> @owned String {
// %0                                             // user: %1
bb0(%0 : $*Bicycle):
  ...
}

sil_witness_table hidden Car: Vehicle module main {
  method #Vehicle.type: <Self where Self : Vehicle> (Self) -> () -> String : @protocol witness for main.Vehicle.type() -> Swift.String in conformance main.Car : main.Vehicle in main   // protocol witness for Vehicle.type() in conformance Car
}

sil_witness_table hidden Truck: Vehicle module main {
  method #Vehicle.type: <Self where Self : Vehicle> (Self) -> () -> String : @protocol witness for main.Vehicle.type() -> Swift.String in conformance main.Truck : main.Vehicle in main // protocol witness for Vehicle.type() in conformance Truck
}

sil_witness_table hidden Bicycle: Vehicle module main {
  method #Vehicle.type: <Self where Self : Vehicle> (Self) -> () -> String : @protocol witness for main.Vehicle.type() -> Swift.String in conformance main.Bicycle : main.Vehicle in main   // protocol witness for Vehicle.type() in conformance Bicycle
}

  1. 通过SIL验证,协议实例调用协议定义的方法,的确为虚表派发
  2. 使用结构体实现协议定义的方法, 这个过程编译器会生成很多胶水代码,并采用虚表派发所以协议定义方法这种方式并不适合大量使用
  3. 按照Apple的建议,使用结构体遵循协议来共享协议实现的方法,采用的是静态派发,也没有胶水代码,可以广泛采用。

动态 VS 静态

默认情况下,Objective-C 使用动态派发。这种派发技术以多态的形式为开发人员提供了灵活性!子类化和覆盖现有的方法和东西,在使用上很棒。但是,这是有代价的。
动态派发以恒定的运行时开销为代价提高了语言的表达能力。这意味着,在动态派发的情况下,对于每个方法调用,我们的编译器都必须查看我们所调用的 vtable(其他语言中的虚拟表或派发表),以检查特定方法的实现。编译器需要确定你是在引用父类的实现,还是在引用子类的实现。由于所有对象的内存都是在运行时分配的,因此编译器只能在运行时执行该检查。
但是,静态派发不存在此问题。使用这种派发技术,编译器在编译时就已经知道了某个方法会调用哪种方法实现。因此,编译器可以执行某些优化,甚至在可能的情况下甚至可以将代码转换为内联,从而使整体执行速度变得更快!

那么,在 Swift 中是如何实现以上两种派发的呢?

  • 为了实现动态派发,需要继承NSObject,对基类进行子类化,然后重写基类的现有方法。另外,我们可以使用 @objc dynamic 关键字,以便将我们的方法公开给 Objective-C 运行时
  • 要实现静态派发,我们需要使用 final 和 static 关键字,因为两者都确保了类和方法不能被覆盖。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift 的函数是怎么派发的呢? 我没能找到一个很简明扼要的答案, 但这里有四个选择具体派发方式的因素存在: 声...
    CrystalZhu阅读 600评论 0 0
  • 编译型语言有三种基础的派发方式: 静态派发;函数表派发;消息机制派发(动态派发).我们都知道Objective-C...
    Zafir_zzf阅读 549评论 2 1
  • 派发方式 (Types of Dispatch ) 函数派发就是程序判断使用哪种途径去调用一个函数的机制. 每次函...
    CrystalZhu阅读 172评论 0 1
  • 介绍 首先全面了解一下,有4种派发机制,而不是两种(静态和动态): 内联(inline) (最快) 静态派发 (S...
    6ffd6634d577阅读 7,979评论 4 127
  • 函数派发方式 能够在编译期确定执行方法的方式叫做静态分派 Static dispatch,无法在编译期确定,只能在...
    文博同学阅读 1,021评论 0 1