Frozen Structs in Swift: Benefits, Examples, and Performance Comparison

Nilaakash Singh
2 min readFeb 4, 2024

Swift’s frozen structs bring a unique perspective to immutability, offering benefits in terms of predictability, safety, and performance.
In this article, we’ll explore the advantages, delve into practical examples using a Decodable model, and conduct a performance comparison between non-frozen and frozen structs.
Let’s get started:

Benefits of Frozen Structs:

1. Immutability for Predictability:

Immutability ensures that once an instance is created, its properties remain unchanged, enhancing code predictability.

Example:

Immutability for Predictability

2. Safer Concurrency:

Immutability simplifies concurrent programming, reducing the risk of data races.

Example:

Safer Concurrency

3. Performance Optimizations:

The @frozen attribute allows the compiler to optimize performance, making assumptions about the immutability of the struct.

Example:

Performance optimizations

4. Value Semantics:

Frozen structs align with Swift’s value semantics, promoting a functional programming style.

Example:

Value Semantics

Performance Comparison:

Let’s compare the performance of non-frozen and frozen structs in a scenario involving frequent modifications.

Scenario: Modifying an Array

Non-frozen Struct:

Mutable Data

Frozen Struct:

Immutable Data

In this scenario, the non-frozen struct allows direct modification of the array, potentially leading to more efficient memory usage. However, the frozen struct requires creating a new instance for each modification, introducing a level of indirection.

Disadvantages and Considerations:

1. Overhead for Copying:

Immutable structures require creating a new instance for each modification, potentially leading to increased memory usage.

Example:

Copying overhead

2. Limited Use Cases:

While powerful, frozen structs may not be suitable for scenarios requiring frequent modifications.

Example:

Limited use case

3. Learning Curve:

Developers new to the concept of frozen structs may find the strict immutability rules initially challenging.

Using Frozen Structs with Decodable Models:

Consider a scenario where immutability is desired for decoding JSON data into a model. Using a frozen struct can provide clarity and safety in this context.

Example:

Frozen struct with decodable data

Conclusion:

Frozen structs in Swift offer a robust approach to immutability, enhancing code predictability and safety. While the performance comparison highlights potential overhead for copying in certain scenarios, careful consideration of your application’s needs will guide you in leveraging the benefits of frozen structs effectively.

Share this blog to spread the knowledge | Do Follow, and CLAP if you Liked it! Happy Coding :)

Add me on Linkedin.

--

--

Nilaakash Singh

Senior iOS Engineer at Loblaw Digital | Swift | SwiftUI | Combine | Swift Async | Blogger.