> For the complete documentation index, see [llms.txt](https://ryukiedev.gitbook.io/wiki/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ryukiedev.gitbook.io/wiki/swift/yi-writing-highperformance-swift-code.md).

# 24.\[译]编写高性能Swift代码-Writing High-Performance Swift Code(2022.8.25版)

## 编写高性能的 Swift 代码

文中的一些 Tips 能够帮助提高 Swift 程序的质量，并提高代码容错性和可读性。

## 一、 开启优化 - Enabling Optimizations

首先你应该做的就是开启优化。Swift 提供了三种优化等级：

* `-Onone`: 标准的开发模式。编译器提供最少的优化并且提供所有 debug 信息。
* `-O`: 生产模式代码。编译器进行大量优化代码。调试信息会提供但是不完整。
* `-Osize`: 一个特殊的模式，编译器会优先考虑代码大小，而不是性能。

在 Xcode 中，Project 的 Build Setting 中搜索 Optimization Level 就可以进行配置。

## 二、 整模块优化 - Whole Module Optimizations (WMO)

默认状态下 Swift 会独立编译每个文件。这使得 Xcode 可以快速的并行编译多个文件。但是，每个文件分开变异阻碍了编译器进行优化。Swift 也可以把整个应用程序作为一个文件进行编译，并作为一个编译单元进行优化。编译会花费更久的时间，但是 run 会更快。

> [Whole-Module Optimization in Swift 3](https://www.swift.org/blog/whole-module-optimizations/)
>
> Xcode 8 默认开启

## 三、 减少动态派发 - Reducing Dynamic Dispatch

Swift 默认是和 Objective-C 一样非常`动态`的语言。与 Objective-C 不同的是，Swift 给了开发者可以通过减少或者避免动态特性，来提升程序运行时性能的能力。

下面由几个例子进行说明：

### 动态派发 - Dynamic Dispatch

类默认对 方法调用 和 属性访问 进行动态派发。例如下面的 `a.aProperty`, `a.doSomething()` and `a.doSomethingElse()` 动态派发的。

```swift
  class A {
    var aProperty: [Int]
    func doSomething() { ... }
    dynamic doSomethingElse() { ... }
  }

  class B: A {
    override var aProperty {
      get { ... }
      set { ... }
    }

    override func doSomething() { ... }
  }

  func usingAnA(_ a: A) {
    a.doSomething()
    a.aProperty = ...
  }
```

在 Swift 里，动态派发默认是间接地通过一个 vtable[^1] 进行调用。如果在声明里加上了 `dynamic` 关键字，Swift 会通过 Objective-C 的消息机制进行调用。两种方式相较于直接调用函数都更慢，因为阻碍了很多 编译器可以进行 优化 的地方，间接调用也多了很多开销。想要提升代码运行性能就需要限制动态特性。

### 建议：使用 `final` 当你确定被声明的不需要被重写

`final` 关键字会限制 `class`、`method`、`property` 不能被重写。这意味着编译器可以`直接调用`函数，而不是`间接调用`。下面的 `C.array1` and `D.array1` 将会被 直接访问 。相对的 `D.array2` 将会被通过一个 `vtable` 调用：

```Swift
  final class C {
    // class 'C' 中所有声明的都不能被重写
    // No declarations in class 'C' can be overridden.
    var array1: [Int]
    func doSomething() { ... }
  }

  class D {
    // array1 不能被计算属性重写
    final var array1: [Int] // 'array1' cannot be overridden by a computed property.
    // array2 能被计算属性重写
    var array2: [Int]      // 'array2' *can* be overridden by a computed property.
  }

  func usingC(_ c: C) {
    // 访问 C.array1 不会经过动态派发
    c.array1[i] = ... // Can directly access C.array without going through dynamic dispatch.
    // 会直接调用 C.doSomething 不会经过虚函数表调用
    c.doSomething() = ... // Can directly call C.doSomething without going through virtual dispatch.
  }

  func usingD(_ d: D) {
    // 直接访问 D.array1 不经过动态派发
    d.array1[i] = ... // Can directly access D.array1 without going through dynamic dispatch.
    // 经过动态派发访问 D.array2
    d.array2[i] = ... // Will access D.array2 through dynamic dispatch.
  }
```

### 建议：使用 `private` 和 `fileprivate` 声明不需要被文件外界访问的内容

使用 `private` 和 `fileprivate` 关键字能够将这些声明的访问限制在该文件内部。这会让编译器能查出所有其它潜在的重写声明。由此编译器能够自动推断 `final` 关键字并删除`方法的间接调用`和`空间访问`。

如下：假设 `E`, `F` 在该文件内没有重写任何声明，那么 `e.doSomething()` 和 `f.myPrivateVar` 就能够被直接访问：

```swift

  private class E {
    func doSomething() { ... }
  }

  class F {
    fileprivate var myPrivateVar: Int
  }

  func usingE(_ e: E) {
    /**
    该文件内没有子类存在
    编译器可以移除 doSomething 的虚表调用，并直接调用 E 的 doSomething 方法
    */
    e.doSomething() // There is no sub class in the file that declares this class.
                    // The compiler can remove virtual calls to doSomething()
                    // and directly call E's doSomething method.
  }

  func usingF(_ f: F) -> Int {
    return f.myPrivateVar
  }
```

### 建议：如果启用了 `WMO`，在模块内部对不需要外部访问的内容使用 `internal` 关键字进行声明

`WMO` 使得编译器将整个模块的代码作为一个整体一次性进行编译。使编译单个声明时能够拥有更广的视野从而进行优化。当一个声明为 `internal` 就不会在模块外部被访问到，优化器可以根据是否存在潜在的声明重写，而自动推断出 `final` 关键字。

> NOTE: 由于现在 Swift 默认的访问级别已经是 `internal`，通过开启 `WMO` 就不用额外的操作（`WMO` 也是默认开启的了）。

## 四、 高效的使用容器类型 - Using Container Types Efficiently

`Swift` 标准库提供了重要功能：通用容器 `Array` 和 `Dictionary`。下面将介绍如何高效的使用这些类型。

### 建议：在数组中使用值类型

在 Swift 中，类型能够被分为两种：`值类型 (structs, enums, tuples)`，`引用类型 (classes)`。一个关键的差别是值类型不能被放入 `NSArray`。因此当使用值类型时，优化器就不需要去处理对 `NSArray` 的兼容。

并且对比引用类型，值类型仅当`包含了引用类型`的时候才需要`引用计数`。通过使用不包含引用类型的值类型，可以避免在 `Array` 内部的 `retain` 和 `release` 减少开销。

```swift

  // Don't use a class here.
  struct PhonebookEntry {
    var name: String
    var number: [Int]
  }

  var a: [PhonebookEntry]
```

需要时刻注意平衡使用`大的值类型`和`引用类型`。有时拷贝移动一个`巨大的值类型`可能消耗比管理一个`引用类型`的 `retain/release` 消耗还要大。

### 建议：不需要考虑 NSArray 桥接的时候可以使用 `ContiguousArray` 来存储引用类型

```swift

  class C { ... }
  var a: ContiguousArray<C> = [C(...), C(...), ..., C(...)]
```

> [Swift标准库源码阅读笔记 - Array和ContiguousArray](https://juejin.cn/post/6844903626264035342)
>
> Array 需要考虑对 NSArray 的兼容，内部存在很多类型检查。

### 建议：使用引用修改而不是对象重新赋值 - Use inplace mutation instead of object-reassignment

在 Swift 标准库中所有的容器类型都是使用了 `COW(copy-on-write)` 机制来替代直接拷贝。在大多数情况下，编译器会引用容器而不是深拷贝。只有当容器的引用计数大于 1 并且容器被修改了，才会触发底层容器的拷贝。

如下：当 `c` 赋值给 `d`，不会触发拷贝。但是当 `d` 通过 `append(2)` 修改的时候，`d` 会先拷贝容器，然后 `2` 会被添加进 `d`：

```swift
  var c: [Int] = [ ... ]
  var d = c        // No copy will occur here.
  d.append(2)      // A copy *does* occur here.
```

如果使用不当，COW 有时会造成没必要的拷贝。例如下面的例子通过在方法内部返回一个新数组，进行对象重新赋值来达到 `append_one`。所有传入的参数都会被 `reatin` 然后在函数结束后 `release`。如果像下面这样实现一个 `append_one` 方法：

```swift
  func append_one(_ a: [Int]) -> [Int] {
    var a = a
    a.append(1)
    return a
  }

  var a = [1, 2, 3]
  a = append_one(a)
```

`a` 可能会被拷贝，尽管 `a` 在 `append_one` 结束后没有被使用。如果使用 `inout` 就可以避免：

```swift
  func append_one_in_place(a: inout [Int]) {
    a.append(1)
  }

  var a = [1, 2, 3]
  append_one_in_place(&a)
```

## 五、 避免检查溢出的计算 - Wrapping operations

Swift 在执行一般整型计算的时候会检查是否溢出。但是在已知不会溢出的场景下依旧这么做就显得非常不合适了，也不符合高性能编码的期望。

### 建议： 在已知不会溢出的情况下使用 `wrapping arithmetic` 进行不检查的整型计算 `&+`

在高性能编码中，如果你确定不会溢出，就可以使用 `wrapping arithmetic` 来避免检查。

```swift
  a: [Int]
  b: [Int]
  c: [Int]

  // Precondition: for all a[i], b[i]: a[i] + b[i] either does not overflow,
  // or the result of wrapping is desired.
  for i in 0 ... n {
    c[i] = a[i] &+ b[i]
  }
```

需要指出的是，`&+` `&-` `&*` 在溢出的时候结果会简单的处理。例如：`Int.max &+ 1` 的结果是 `Int.min`（不像C语言里，`INT_MAX + 1` 是为无法定义的操作）。

## 六、 范型 - Generics

Swift 通过范型提供了非常强大的抽象能力。Swift 编译器通过 `MySwiftFunc<T>` 生成可以为 `T` 执行的代码块。生成的代码块包含一个函数指针列表和一个包含 `T` 容器作为参数。`MySwiftFunc<Int>` 和 `MySwiftFunc<String>` 的不同表现，是通过传递不同的函数列表和容器大小来决定的。一个范型例子：

```swift
  class MySwiftFunc<T> { ... }

  // 生成为 Int 工作的代码
  MySwiftFunc<Int> X    // Will emit code that works with Int...
  // 生成为 String 工作的代码
  MySwiftFunc<String> Y // ... as well as String.
```

当开启了优化，Swift 编译器会检查每个调用调用，并检查其中使用的类型（比如非范型类型）。如果范型函数的定义对优化器是可见的并且类型是已知的，Swift 编译器将会生成一个针对这个特定类型版本的函数。这个过程叫做 `specialization（定制化）`，可以避免一些范型相关的消耗。如下例子：

```swift
  class MyStack<T> {
    func push(_ element: T) { ... }
    func pop() -> T { ... }
  }

  func myAlgorithm<T>(_ a: [T], length: Int) { ... }

  // The compiler can specialize code of MyStack<Int>
  // 编译器会为范型 MyStack<Int> 生成特定代码
  var stackOfInts: MyStack<Int>

  // Use stack of ints.
  for i in ... {
    stack.push(...)
    stack.pop(...)
  }

  var arrayOfInts: [Int]
  // The compiler can emit a specialized version of 'myAlgorithm' targeted for
  // [Int]' types.
  // 编译器会生成针对 [Int] 版本的函数
  myAlgorithm(arrayOfInts, arrayOfInts.length)
```

### 建议： 将范型声明放在需要使用它的模块内

优化器只能对声明在当前模块中的范型定义进行特化处理。如果 `WMO` 没有开启，即只会当声明和调用在同一个文件的时候才会处理。

> **NOTE:** 标准库是个特例。定义在标准库中的对所有模块可见并可以被特化处理。

## 七、 Swift 中较大值类型的开销 - The cost of large Swift values

在 Swift 中，一些较大的值类型如果进行拷贝会比较耗时，并影响性能。

[More on value types](https://developer.apple.com/swift/blog/?id=10)

下面使用值类型定义了一个 `Tree`。其节点包含了其他同样遵守 P协议 的节点。计算机图形场景下经常由可以用值类型表示的不同的`实体entities`和`变体transformations`构成。

[面向协议编程 Protocol-Oriented-Programming](https://developer.apple.com/videos/play/wwdc2015-408/)

```swift

  protocol P {}
  struct Node: P {
    var left, right: P?
  }

  struct Tree {
    var node: P?
    init() { ... }
  }
```

当一个 tree 被拷贝，真个 tree 都要被拷贝。这里对于我们的 tree 来说是一个开销很大的操作，需要大量的执行 malloc/free 并校验引用计数。

然而我们并不关心这些值是否被拷贝，只要它还在内存中可以被正常使用。

### 建议： 较大的值类型使用写时复制 COW - Advice: Use copy-on-write semantics for large values

写时复制能够解决值类型大量拷贝的问题。实现写时拷贝最简单的方式就是使用现成的 COW 数据结构，比如 Array。Swift 的 Array 是值类型。但是 Array 的内容不会每次都拷贝，因为使用来写时复制。

我们使用 Array 改造 Tree 可以避免大量的拷贝操作。这提升了 Tree 数据结构的性能表现，并且将传递一个数组的时间复杂度由`O(n)`降低到了`O(1)`。

```swift
  struct Tree: P {
    var node: [P?]
    init() {
      node = [thing]
    }
  }
```

使用数组来实现 `COW` 机制有两个明显的缺点:

* 第一个问题就是数组中类似 `"append"` 和 `"count"` 的方法，它们在值封装中没有任何作用。这些方法让引用封装变得很不方便。我们可以通过创建一个隐藏未用到的 API 的封装结构来解决这个问题，并且优化器会移除它的开销，但是这样的封装并不能解决第二个问题。
* 第二个问题就是数组内存在保证程序安全性和与 Objective-C 进行交互的代码， Swift 会检查索引访问是否在数组边界内，以及保存值时会判断数组存储时否需要扩展存储空间。这些操作运行时都会降低程序速度。

一个替代方法就是实现一个 `copy-on-write` 机制的数据结构来代替数组作为值封装。下面的例子就是介绍如何构建一个这样的数据结构：

> Note: 这样的解决办法，对于嵌套结构并非最优，并且一个基于 COW 数据结构的 addressor 会更加高效。然而在这种情况下，抛开标准库执行 addressor 是行不通的。 [More details in this blog post by Mike Ash](https://www.mikeash.com/pyblog/friday-qa-2015-04-17-lets-build-swiftarray.html)

```swift
final class Ref<T> {
  var val: T
  init(_ v: T) { val = v }
}

struct Box<T> {
  var ref: Ref<T>
  init(_ x: T) { ref = Ref(x) }

  var value: T {
    get { return ref.val }
    set {
      if !isKnownUniquelyReferenced(&ref) {
        ref = Ref(newValue)
        return
      }
      ref.val = newValue
    }
  }
}
```

Box 类型可以代替上个例子中的数组。

## 八、 不安全的代码 - Unsafe code

Swift 中类总是采用引用计数。 Swift 编译器会在每次对象被访问时插入增加引用计数的代码。例如，考虑一个通过使用类实现遍历链表的例子。遍历链表是通过从一个节点到下一个节点移动引用实现： `elem = elem.next`。每次我们移动这个引用， Swift 将会增加 next 对象的引用计数，并且减少前一个对象的引用计数。这样的引用计数方法成本很高，但只要我们使用 Swift 的类就无法避免。

```swift

  final class Node {
    var next: Node?
    var data: Int
    ...
  }
```

### 建议：使用非托管的引用来避免引用计数带来的开销

> Note: `Unmanaged<T>._withUnsafeGuaranteedRef` 不是公开的 API，并且今后将会被移除。`所以不要使用它`。

在性能优先代码中，你可以选择使用未托管的引用。其中 `Unmanaged<T>` 结构体就允许开发者关闭对于特殊引用的自动引用计数 (ARC) 功能。

当你这样做了，你需要确保有另外的引用引用这个被 `Unmanaged` 的实例，来保证在使用 `Unmanaged` 期间实例不会释放。

```swift

  // The call to ``withExtendedLifetime(Head)`` makes sure that the lifetime of
  // Head is guaranteed to extend over the region of code that uses Unmanaged
  // references. Because there exists a reference to Head for the duration
  // of the scope and we don't modify the list of ``Node``s there also exist a
  // reference through the chain of ``Head.next``, ``Head.next.next``, ...
  // instances.

  withExtendedLifetime(Head) {

    // Create an Unmanaged reference.
    var Ref: Unmanaged<Node> = Unmanaged.passUnretained(Head)

    // Use the unmanaged reference in a call/variable access. The use of
    // _withUnsafeGuaranteedRef allows the compiler to remove the ultimate
    // retain/release across the call/access.

    while let Next = Ref._withUnsafeGuaranteedRef { $0.next } {
      ...
      Ref = Unmanaged.passUnretained(Next)
    }
  }
```

> [Unmanaged.swift](https://github.com/apple/swift/blob/main/stdlib/public/core/Unmanaged.swift)
>
> [Unmanaged](https://developer.apple.com/documentation/swift/unmanaged/)

## 九、 协议 - Protocols

### 建议：将智能由 class 实现的协议标记为 class-protocol

Swift 可以限定协议只能通过类实现。标记协议只能由类实现的一个优点就是，编译器可以基于只有类实现协议这一事实来优化程序。

例如，如果 ARC 内存管理系统知道正在处理类对象，那么就能够简单的保留(增加对象的引用计数)它。如果编译器不知道这一事实，它就不得不假设结构体也可以实现协议，那么就需要准备保留或者释放不可忽视的结构体，这样做的代价很高。

**如果限定只能由类实现某个协议，那么就需要标记类实现的协议为类协议，以便获得更好的运行性能。**

```swift
  protocol Pingable: AnyObject { func ping() -> Int }
```

[Protocols](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html)

## 十、 left/var 被逃逸闭包捕获的性能消耗

可能很多人认为 let 和 var 的区别仅仅是语义层面的，起始其中也有性能方面的思考。一旦一个变量和一个闭包发生了绑定，就强制编译器生成一个逃逸闭包。例如：

```swift
  let f: () -> () = { ... } // Escaping closure
  // Contrasted with:
  ({ ... })() // Non Escaping closure
  x.map { ... } // Non Escaping closure
```

当一个 var 被逃逸闭包捕获，编译器必须在堆上开辟空间来存储这个 var 使得，创建者和闭包都能够读写这个 var。相对的当捕获一个 let。会直接在闭包的数据结构内添加一个该变量的 copy，而不用去堆上开辟空间。

### 建议：如果闭包不是真的需要逃逸，使用 `inout` 参数传递 var

`inout` 会确保不会在堆上再去开辟空间，避免了没必要的 retain/release 操作。

## 补充说明 - Footnotes

1. This is due to the compiler not knowing the exact function being called.
2. An optimization technique in which a copy will be made if and only if a modification happens to the original copy, otherwise a pointer will be given.

[^1]: A virtual method table or 'vtable' is a type specific table referenced by instances that contains the addresses of the type's methods. Dynamic dispatch proceeds by first looking up the table from the object and then looking up the method in the table.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ryukiedev.gitbook.io/wiki/swift/yi-writing-highperformance-swift-code.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
