I wonder if-let memory allocation.

var name: String? = "name"
if let copyname = name {
      print(copyname)
}

In this code, are name and copyname allocated in two different memory?

Answered by mikeyh in 724037022

String is a special case which uses copy-on-write optimisations so the underlying buffer can be shared by different copies of a string.

Note the use of can as there are other factors that could impact this eg small string optimisations, bridging, compiler optimisations, etc.

https://developer.apple.com/documentation/swift/string#Performance-Optimizations

Consider the following:

          var name: String? = "name"
          if let copyname = name {
               name = "newName"
               print("name", name)
               print("copyname", copyname)
          }

If they pointed to the same memory, you should get "newName" in copyname.

You get:

name Optional("newName")
copyname name
Accepted Answer

String is a special case which uses copy-on-write optimisations so the underlying buffer can be shared by different copies of a string.

Note the use of can as there are other factors that could impact this eg small string optimisations, bridging, compiler optimisations, etc.

https://developer.apple.com/documentation/swift/string#Performance-Optimizations

I wonder if-let memory allocation.
 
 
Q