What is the cost of doing Swift?

What are the different runtime costs associated with the following type cast?

  • Numeric number of constants , for example:

    let f = 0.1 as CGFloat 

    I would suggest that this has a zero execution cost.

  • Numeric value of the run time , for example:

     let f = someDoubleValue as CGFloat 

    I would suggest that this has a very low execution cost.

  • Upcast , for example:

     let dict: [String: Int] = ... let anyObj = dict as AnyObject 

    I expect this to have a zero execution cost.

  • Fault tolerant , for example:

     let anyObj: AnyObject = ... if let str = anyObj as? String { ... } 

    I expect this to have a cost of execution proportional to the number of classes in the hierarchy of the dynamic type anyObj .

  • Forced Downcast , for example:

     let anyObj: AnyObject = ... let str = anyObj as! String 

    Maybe the cost of forced reduction is slightly lower?

  • Forced emptying of a collection , for example:

     let dates: [AnyObject] = ... for date in dates as! [NSDate] { ... } 

    What happens here, especially when dates comes from NSArray ? Is the cost of fulfilling this role proportional to the number of its elements? What should I do if I move to a more complex type of collection, for example [String: [String: [Int]]] - this is the whole collection that has passed the test to make sure that all its elements and sub-elements correspond to this cast?

For each of the first four cases, are my statements true?

+8
casting time-complexity swift overhead
source share
1 answer
  • This is O (1) (almost 0) if it is explicitly deprived (e.g. numerical casting and boost): case 1, 2, 3.

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

  • To collect downcastings:

    • as? - O (n), because checking the type of the element is being done with impatience.
    • Stressful forced downcasting is O (1) because the item type check is delayed: case 6.
    • Bridge Forced NSArray as! [NSDate] ( NSArray as! [NSDate] ) is O (n), because the element type check is being done with impatience.
    • Nested collections are recursively rendered, so you just apply the above rules recursively.

Sources:

+11
source share

All Articles