gpt4 book ai didi

swift - NSNotificationCenter 与委托(delegate)——哪个更快?

转载 作者:IT王子 更新时间:2023-10-29 05:25:04 25 4
gpt4 key购买 nike

我已经阅读了很多有关每种方法的优缺点的文章,而且我知道委托(delegate)通常是针对一个听众的,而通知是针对许多听众的。问题在于性能。

我已阅读 NSNotificationCenter vs delegation( using protocols )?

我正在通过通知将音频信号从麦克风发送到另一个类(class)。我知道在这里我应该使用委托(delegate),但我的问题是委托(delegate)会更快吗?

我有帧率下降的问题,我想知道原因是否可能是使用通知而不是委托(delegate),或者两者之间没有关系?

最佳答案

对于那些对性能感兴趣的人,我使用 XCTest 框架的 measureBlock API 在 swift 中运行了一个简单的测试。简短的回答是,如果在循环中调用,差异将是显着的。

这里是用来测试的代码:

public protocol MyTestClassDelegate: class {
func myTestDelegateCallback()
}

public let TestClassValueChangedNotification = "TestClassNotification"

public class MyViewModel {
public weak var delegate: MyTestClassDelegate?
public init() { }
public func doNotification() {
NSNotificationCenter.defaultCenter().postNotificationName(TestClassValueChangedNotification, object: nil)
}

public func doDelegation(value: Int) {
delegate?.myTestClassDelegateCallback()
}
}

和测试用例:

func testPerformanceNotifiction() {
measureBlock { () -> Void in
let testClass = MyTestClass()
for i in 0...100000 {
testClass.doNotification(i)
}
}
}

func testPerformanceDelegation() {
measureBlock { () -> Void in
let testClass = MyTestClass()
testClass.delegate = self
for i in 0...100000 {
testClass.doDelegation(i)
}
}
}

Results:
- Delegation:- - - - - - 0.957 seconds
- Notification Center: - 3.882 seconds

我试过的一个糟糕的选择

其他考虑因素是 NSNotificationCenter 的性能显然可能会根据给定事件的监听器数量以及这些监听器执行的代码的性能而有所不同。还值得注意的是,NSNotificationCenter 同步调用通知监听器,并且在调用 postNotification 的同一线程上,这可能是第一次接近 NSNotificationCenter 时的陷阱。

如果您发现自己处于需要一对多通信和高性能的场景中(就像我遇到的那样),您可能会考虑简单地实现一组委托(delegate)。但你不必费心,因为这样做的性能实际上是最差的选择。

public func doMultipleDelegatation() {
for i in 0..<delegates.count {
delegates[i].myTestDelegateCallback()
})
}

func testPerformanceMultipleDelegation() {
measureBlock { () -> Void in
let testClass = MyTestClass()
testClass.delegates = [self]
for i in 0...100000 {
testClass.doMultipleDelegation(i)
}
}
}

Final Results:
- Delegation:- - - - - - 0.957 seconds
- Notification Center: - 3.882 seconds
- Multiple Delegation: - 6.488 seconds

关于swift - NSNotificationCenter 与委托(delegate)——哪个更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17921155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com