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:
-
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 ofURL
is not known until runtime. -
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 theURL
on the heap and free it when it goes out of scope. This dynamic allocation is necessary because the size ofURL
is not known at compile time.
For more details, you can refer to the session Explore Swift performance (22:01).
Relevant Sessions
Explore Swift performance
Discover how Swift balances abstraction and performance. Learn what elements of performance to consider and how the Swift optimizer affects them. Explore the different features of Swift and how they’re implemented to further understand the tradeoffs available that can impact performance.
What’s new in Swift
Join us for an update on Swift. We’ll briefly go through a history of Swift over the past decade, and show you how the community has grown through workgroups, expanded the package ecosystem, and increased platform support. We’ll introduce you to a new language mode that achieves data-race safety by default, and a language subset that lets you run Swift on highly constrained systems. We’ll also explore some language updates including noncopyable types, typed throws, and improved C++ interoperability.
Analyze heap memory
Dive into the basis for your app’s dynamic memory: the heap! Explore how to use Instruments and Xcode to measure, analyze, and fix common heap issues. We’ll also cover some techniques and best practices for diagnosing transient growth, persistent growth, and leaks in your app.