Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Swift String to NSString bridging overhead?

I've started to learn Swift. And I read, that Swift String is bridged to NSString when using Cocoa classes. What is an overhead of this operation?

like image 780
Semyon Avatar asked Dec 19 '15 17:12

Semyon


Video Answer


1 Answers

From the iOS Developer Library

Swift automatically bridges between the String type and the NSString class.

From the Swift source -> stdlib/public/core/String.swift

String is bridged to Objective-C as NSString, and a String that originated in Objective-C may store its characters in an NSString. Since any arbitrary subclass of NSString can become a String, there are no guarantees about representation or efficiency in this case. Since NSString is immutable, it is just as though the storage was shared by some copy: the first is any sequence of mutating operations causes elements to be copied into unique, contiguous storage which may cost O(N) time and space, where N is the length of the string representation (or more, if the underlying NSString has unusual performance characteristics).

These are my conclusions from that paragraph. Note: NSString is immutable, I'm not sure how NSMutableString works which may be relevant depending on your specific case.

  1. Bridging an NSString to String is essentially a free operation; no conversion is necessary. O(1)
    • NSString uses UTF-16 as it's backing store. String uses UTF-16 or ASCII so the two instances can use the same memory.
  2. However, if you then mutate that String struct, all of the memory will need to be copied from the original NSString. O(N)
    • String can't modify its backing memory without also modifying the NSString's memory. This is why the memory must be copied so String has it's own memory.

Source code for the backing StringCore that swift uses.

like image 138
Kevin Avatar answered Nov 15 '22 04:11

Kevin