What is the runtime cost of Swift's casts?

  • It is O(1) (almost 0) if it is obviously castable(like numeric casting and upcasting): case 1, 2, 3.

  • For other non-collection castings, it is obviously O(1): case 4, 5.

  • For collection downcastings:

    • as? is O(n) because element type checking is performed eagerly.
    • Native forced downcasting is O(1) because element type checking is deferred: case 6.
    • Bridged forced downcasting(NSArray as! [NSDate]) is O(n) because element type checking is performed eagerly.
    • Nested collections are recursively casted so you just apply the above rules recursively.

Sources:

  1. https://github.com/apple/swift/blob/master/stdlib/public/runtime/Casting.cpp
  2. https://github.com/apple/swift/blob/master/stdlib/public/core/ArrayCast.swift
  3. https://github.com/apple/swift/blob/master/stdlib/public/core/HashedCollections.swift.gyb