13

我喜欢 swift 中的值语义,但我担心变异函数的性能。假设我们有以下struct

struct Point {
   var x = 0.0
   mutating func add(_ t:Double){
      x += t
   }
}

现在假设我们创建一个Point并对其进行变异:

var p = Point()
p.add(1)

现在struct内存中的现有是否会发生突变,或者被self替换为新实例,如

self = Point(x:self.x+1)
4

3 回答 3

15

现在内存中的现有结构是否发生突变,或者被新实例自我替换

从概念上讲,这两个选项完全相同。我将使用这个示例结构,它使用 UInt8 而不是 Double(因为它的位更容易可视化)。

struct Point {
    var x: UInt8
    var y: UInt8

    mutating func add(x: UInt8){
       self.x += x
    }
}

并假设我创建了这个结构的一个新实例:

var p = Point(x: 1, y: 2)

这会在堆栈上静态分配一些内存。它看起来像这样:

00000000  00000001  00000010  00000000
<------^  ^------^  ^------^ ^----->
other    | self.x | self.y | other memory
          ^----------------^
          the p struct

让我们看看当我们调用时在这两种情况下会发生什么p.add(x: 3)

  1. 现有结构在原地发生变异:

    我们在内存中的结构将如下所示:

    00000000  00000100  00000010  00000000
    <------^  ^------^  ^------^ ^----->
    other    | self.x | self.y | other memory
            ^----------------^
            the p struct
    
  2. Self 被一个新实例替换:

    我们在内存中的结构将如下所示:

    00000000  00000100  00000010  00000000
    <------^  ^------^  ^------^ ^----->
    other    | self.x | self.y | other memory
            ^----------------^
            the p struct
    

请注意,这两种情况之间没有区别。那是因为为 self 分配一个新值会导致就地突变。p总是相同的两个字节的内存在堆栈上。为 self 分配一个新值p只会替换这两个字节的内容,但它仍然是相同的两个字节。

现在这两种情况之间可能存在一个区别,即处理初始化程序的任何可能的副作用。假设这是我们的结构,而不是:

struct Point {
    var x: UInt8
    var y: UInt8

    init(x: UInt8, y: UInt8) {
        self.x = x
        self.y = y
        print("Init was run!")
    }

    mutating func add(x: UInt8){
       self.x += x
    }
}

当你运行时var p = Point(x: 1, y: 2),你会看到它Init was run!被打印出来(如预期的那样)。但是当你运行时p.add(x: 3),你会看到没有进一步打印。这告诉我们初始化器不是新的。

于 2017-02-23T16:22:17.760 回答
13

我觉得值得一看(从相当高的层次上)编译器在这里做了什么。如果我们看一下针对以下情况发出的规范 SIL:

struct Point {
    var x = 0.0
    mutating func add(_ t: Double){
        x += t
    }
}

var p = Point()
p.add(1)

我们可以看到该add(_:)方法被发出为:

// Point.add(Double) -> ()
sil hidden @main.Point.add (Swift.Double) -> () :
           $@convention(method) (Double, @inout Point) -> () {
// %0                                             // users: %7, %2
// %1                                             // users: %4, %3
bb0(%0 : $Double, %1 : $*Point):

  // get address of the property 'x' within the point instance.
  %4 = struct_element_addr %1 : $*Point, #Point.x, loc "main.swift":14:9, scope 5 // user: %5

  // get address of the internal property '_value' within the Double instance.
  %5 = struct_element_addr %4 : $*Double, #Double._value, loc "main.swift":14:11, scope 5 // users: %9, %6

  // load the _value from the property address.
  %6 = load %5 : $*Builtin.FPIEEE64, loc "main.swift":14:11, scope 5 // user: %8

  // get the _value from the double passed into the method.
  %7 = struct_extract %0 : $Double, #Double._value, loc "main.swift":14:11, scope 5 // user: %8

  // apply a builtin floating point addition operation (this will be replaced by an 'fadd' instruction in IR gen).
  %8 = builtin "fadd_FPIEEE64"(%6 : $Builtin.FPIEEE64, %7 : $Builtin.FPIEEE64) : $Builtin.FPIEEE64, loc "main.swift":14:11, scope 5 // user: %9

  // store the result to the address of the _value property of 'x'.
  store %8 to %5 : $*Builtin.FPIEEE64, loc "main.swift":14:11, scope 5 // id: %9

  %10 = tuple (), loc "main.swift":14:11, scope 5
  %11 = tuple (), loc "main.swift":15:5, scope 5  // user: %12
  return %11 : $(), loc "main.swift":15:5, scope 5 // id: %12
} // end sil function 'main.Point.add (Swift.Double) -> ()'

(通过运行xcrun swiftc -emit-sil main.swift | xcrun swift-demangle > main.silgen

这里重要的是 Swift 如何处理隐式self参数。您可以看到它已作为@inout参数发出,这意味着它将通过引用传递给函数。

为了执行x属性的突变,使用SILstruct_element_addr指令来查找其地址,然后查找. 然后将得到的双精度值与指令一起简单地存储回该地址。_valueDoublestore

这意味着该add(_:)方法能够直接更改内存中p'x属性的值,而无需创建Point.

于 2017-02-23T17:12:27.307 回答
1

我这样做了:

import Foundation

struct Point {
  var x = 0.0
  mutating func add(_ t:Double){
    x += t
  }
}

var p = Point()

withUnsafePointer(to: &p) {
  print("\(p) has address: \($0)")
}

p.add(1)

withUnsafePointer(to: &p) {
  print("\(p) has address: \($0)")
}

并在输出中获得:

点(x:0.0)的地址:0x000000010fc2fb80

点(x:1.0)的地址:0x000000010fc2fb80

考虑到内存地址没有改变,我敢打赌这个结构是变异的,而不是被替换的。

要完全替换某些东西,您必须使用另一个内存地址,因此将原始内存地址中的对象复制回来是没有意义的。

于 2017-02-23T16:24:36.993 回答