What is an immortal static String?

I saw the phrase immortal static string in this post by @MahdiBM.

I just want to check my understanding: Are all the strings below immortal static?

let fubar: String = "Failed unibus address"

let g: String = "23 is a prime"

func foo () -> Void {
   // 
   let u: String = "23 is a prime"
   let v: String = "23 is a prime"
   let w: String = "23 is a prime"

   inspect (string: u)
   inspect (string: v)
   inspect (string: w)
}

struct S1 {
   let u: String = "23 is a prime"
}

struct S2 {
   static let v: String = "23 is a prime"
}

Note that the string "23 is a prime" is repeated six times.

How many instances of it are allocated? one or six?

Zero are allocated. One is emitted into the compiled program.

4 Likes

I'd recommend to consider longer than 15 byte strings to prevent them being stored trivially (inline).

1 Like

Thank you, @David_Smith

If they were in different files, one per file would be emitted, and there would be as many copies of it in the executable?

Compilers and linkers have been deduplicating strings for decades. Swift is no different. To the limits possible at compile time, identical strings are deduplicated and you shouldn't see more than one copy of a (longer-than-15-byte) string in any given executable or library.

2 Likes

It's already been answered, but a fun thing you might like to see is the Godbolt Compiler Explorer . You can use it to compare different compilers and options without needing to install them locally

1 Like

Some info from the stdlib doc that I found useful for strings generally:

b63: isImmortal: Should the Swift runtime skip ARC
    - Small strings are just values, always immortal
    - Large strings can sometimes be immortal, e.g. literals
3 Likes