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?
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 asNSString
, and aString
that originated in Objective-C may store its characters in anNSString
. Since any arbitrary subclass ofNSString
can become aString
, there are no guarantees about representation or efficiency in this case. SinceNSString
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 costO(N)
time and space, whereN
is the length of the string representation (or more, if the underlyingNSString
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.
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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With