简体   繁体   中英

swift typecasting performance cost

I am trying to keep my func update:currentTime as fast as possible. This function was overridden from the SKScene class and gets called around 2000 to 4000 times a second. 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. Note: I make reference to two separate func update methods here.

Will my performance be shot if I typecast 4000 times a second? More importantly, how expensive is a typecast in 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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