每次我将一个新节点附加到Linkedlist时,如果Linkedlist是一个结构,它似乎都会创建一个新的Linkedlist。这对性能不利吗? 将Linkedlist设为类而不是struct会更好吗?
Example
public class Node<Value> {
public var value: Value
public var next: Node?
public init(value: Value, next: Node? = nil) {
self.value = value
self.next = next
}
}
public struct LinkedList<Value> {
public var head: Node<Value>?
public var tail: Node<Value>?
public init() {}
public var isEmpty: Bool {
return head == nil
}
public mutating func push(_ value: Value) {
head = Node(value: value, next: head)
if tail == nil {
tail = head
}
}
public mutating func append(_ value: Value) {
guard !isEmpty else {
push(value)
return
}
}
}
var list = LinkedList<Int>()
list.push(3)
print(Unmanaged<AnyObject>.passUnretained(list as AnyObject).toOpaque())
list.push(2)
print(Unmanaged<AnyObject>.passUnretained(list as AnyObject).toOpaque())
Output
0x000060c0002415f0
0x000060c0002416e0