gpt4 book ai didi

ios - 为什么 swift 函数这么贵?

转载 作者:搜寻专家 更新时间:2023-10-31 22:12:04 25 4
gpt4 key购买 nike

为什么 swift 函数这么贵?

我一直在使用 SpriteKit 编写应用程序。每一帧,我都会在 update() 函数中重新计算 CameraNode 的位置。让我们称之为 //(cameraNodeCode)。当前设置对每秒帧数影响不大,保持在 60。

override func update() {
//(cameraNodeCode)
}

由于 cameraNodeCode 相当大,我认为最好简化我的代码并将其放入一个函数中:updateCameraNode()。现在这就是我所拥有的:

func updateCameraNode() {
//(cameraNodeCode)
}

override func update() {
updateCameraNode()
}

当我这样设置代码时,每秒帧数突然下降到 20。我感到非常惊讶,因为我认为函数的调用成本不会这么高。我决定用这段代码来检验我的理论:

func emptyFunction() {

}

override func update() {
emptyFunction()
emptyFunction()
emptyFunction()
emptyFunction()
emptyFunction()
}

正如我预测的那样,当我这样做时,每秒帧数急剧下降,降至每秒 4.1 帧!

我的问题是:

  • 为什么会这样?是不是像我想的那样,因为简单地调用一个函数太昂贵了,还是我遗漏了什么?
  • 有没有一种方法可以让我的代码看起来简单而不用每秒 20 帧?

更新

我遗漏的关键信息是我使用的是 Xcode Playground 。我认为这是 SpriteKit 和 Playground 的错误。我已经向 Apple 提交了一份错误报告,所以我会看看它对我有何帮助。

最佳答案

说到 Sprite-kit,我已经在新的“Hello world”模板中针对我的 iPhone 7 测试了您的代码:

import SpriteKit
class GameScene: SKScene {
private var label : SKLabelNode?
override func didMove(to view: SKView) {

// Get label node from scene and store it for use later
self.label = self.childNode(withName: "//helloLabel") as? SKLabelNode
if let label = self.label {
label.alpha = 0.0
label.run(SKAction.fadeIn(withDuration: 2.0))
}
}
func emptyFunction() {}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
//emptyFunction()
//emptyFunction()
//emptyFunction()
//emptyFunction()
//emptyFunction()
}
}

如果我不注释更新方法中的行(删除//),则不会发生任何变化。我总是60fps。检查您的项目以找出导致 fps 急剧下降的行,或者如果您在模拟器上测试代码,请尝试在真实设备上测试。希望对您有所帮助。

关于ios - 为什么 swift 函数这么贵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43040859/

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