简体   繁体   English

快速类型转换性能成本

[英]swift typecasting performance cost

I am trying to keep my func update:currentTime as fast as possible.我试图保持我的func update:currentTime尽可能快。 This function was overridden from the SKScene class and gets called around 2000 to 4000 times a second.这个函数被SKScene类覆盖, SKScene被调用大约 2000 到 4000 次。 I want to loop through all the scene's children and do an optional typecast to see if a child implements my Observer interface and then call update on that.我想遍历场景的所有子项并进行可选的类型转换以查看子项是否实现了我的Observer接口,然后对其调用更新。 Note: I make reference to two separate func update methods here.注意:我在这里参考了两个单独的func update方法。

Will my performance be shot if I typecast 4000 times a second?如果我每秒打字 4000 次,我的表演会被拍吗? More importantly, how expensive is a typecast in Swift?更重要的是,Swift 中的类型转换有多昂贵?

Code for context:上下文代码:

// Called inside func update:currentTime
let children = self.children
    for child in children {
        if let observer = child as? TimerObserver {
            observer.update()
        }
    }

Thanks!谢谢!

It depends.这取决于。 Casting from eg int to float will cost as the compiler will create real code to convert the one into the other.从例如intfloat转换会产生成本,因为编译器将创建真正的代码来将一个转换为另一个。

In contrast an object type cast is at no cost.相比之下,对象类型转换是免费的。 It's just that eventually a method call will fail as the cast type is not what you tell it should be.只是最终方法调用会失败,因为转换类型不是您告诉它应该的类型。 It's just that you pretend the object pointer will point to some legal object.只是您假装对象指针将指向某个合法对象。 The pointer itself is not changed.指针本身没有改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM