Foundation has URL struct, which is non-frozen. Where it allocated?

Generated on 8/6/2024

1 search

The URL struct in Foundation is non-frozen, meaning its layout is not known at compile time and can change in future OS updates. Because of this, the memory allocation for a URL instance depends on the context in which it is used:

  1. Global Variables: If you declare a global variable of type URL, the compiler will create a global variable of pointer type. When you access this global variable for the first time, Swift will lazily allocate space for it on the heap. This is because the compiler can only request constant amounts of global memory, and the actual size of URL is not known until runtime.

  2. Local Variables: For local variables, the call frame must have a constant size. Therefore, the call frame will contain a pointer to the URL. When the variable comes into scope, the function will dynamically allocate memory for the URL on the heap and free it when it goes out of scope. This dynamic allocation is necessary because the size of URL is not known at compile time.

For more details, you can refer to the session Explore Swift performance (22:01).

Relevant Sessions

  1. Explore Swift performance
  2. Analyze heap memory