gpt4 book ai didi

ios - 频繁使用计算属性访问对象是否会影响性能?

转载 作者:行者123 更新时间:2023-11-28 08:46:35 25 4
gpt4 key购买 nike

我正在使用 GameplayKit 和 SpriteKit 框架编写游戏。在 Apple 关于 GameplayKit 的示例中,您经常会看到以下内容:

class PlayerEntity: GKEntity {
// MARK: Components

var renderComponent: RPRenderComponent {
guard let renderComponent = componentForClass(RPRenderComponent.self) else {
fatalError()
}
return renderComponent
}
var stateMachineComponent: RPStateMachineComponent {
guard let stateMachineComponent = componentForClass(RPStateMachineComponent.self) else {
fatalError()
}
return stateMachineComponent
}
// MARK: Initialisation
override init() {
super.init()

let renderComponent = RPRenderComponent()
renderComponent.node.entity = self;
let stateMachineComponent = RPStateMachineComponent(states: [
RPPlayerStandingState(entity: self),
RPPlayerFallingState(entity: self),
RPPlayerBouncingDownState(entity: self),
RPPlayerBouncingUpState(entity: self),
RPPlayerJumpingState(entity: self),
RPPlayerBoostState(entity: self)
])
addComponent(renderComponent)
addComponent(stateMachineComponent)
}
}

组件在它们所属的类的初始化期间被创建和初始化,并通过addComponent(component: GKComponent)添加到components-array。

为了使这些组件可以从类 Apple 示例的外部访问,总是使用调用 componentForClass() 的计算属性来返回相应的组件实例。

然而,渲染组件是“逐帧”访问的,这意味着在每个更新周期中,我都需要调用渲染组件,这将导致调用计算属性,在我看来,这会导致额外且可避免的处理负载。

调用看起来像:

func update(withDeltaTime time: NSTimeInterval) {
playerEntity.renderNode.DoSomethingPerFrame()
}

我不是这样做的,而是像下面这样:

class PlayerEntity: GKEntity {
// MARK: Components

let renderComponent: RPRenderComponent
var stateMachineComponent: RPStateMachineComponent!

// MARK: Initialisation
override init() {
renderComponent = RPRenderComponent()
super.init()
renderComponent.node.entity = self

stateMachineComponent = RPStateMachineComponent(states: [
RPPlayerStandingState(entity: self),
RPPlayerFallingState(entity: self),
RPPlayerBouncingDownState(entity: self),
RPPlayerBouncingUpState(entity: self),
RPPlayerJumpingState(entity: self),
RPPlayerBoostState(entity: self)
])
addComponent(renderComponent)
addComponent(stateMachineComponent)

}
}

我没有使用计算属性来访问组件,而是在我的类中持有对它的强引用。在我看来,我在调用计算属性时避免了额外的开销,因为我避免了这种“计算”。

但我不太确定为什么 Apple 使用计算属性来做到这一点。也许我对计算属性的理解完全错误,或者这只是因为这是编写该示例的人的编码风格!?

计算属性会影响性能吗?它们是否自动意味着更多开销?

或者:

这样使用计算属性是否可行且“安全”(就资源而言)? (在我看来,尽管担心计算属性是一个相当优雅的解决方案,顺便说一句。)

最佳答案

这取决于 - 每次属性(property)计算的成本是多少,以及您进行计算的频率。

一般来说,如果计算成本低到几乎没有什么区别,你应该使用计算属性,如果需要更长的时间,你应该使用计算属性。或者,如果计算属性经常返回相同的结果,则计算属性可以缓存它的值。

使用得当,成本非常低。您还需要建议一种易于使用且速度更快的计算属性的替代方案。

关于ios - 频繁使用计算属性访问对象是否会影响性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35134368/

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