Skip to content

Instantly share code, notes, and snippets.

@avii-7
Last active July 14, 2024 17:41
Show Gist options
  • Save avii-7/61b26a8e339aa646d25162d66730ec3b to your computer and use it in GitHub Desktop.
Save avii-7/61b26a8e339aa646d25162d66730ec3b to your computer and use it in GitHub Desktop.
Swift Learnings

Swift — “copy-on-write”

"copy on write" is an optimization technique that helps in managing memory more efficiently.

It is used primarly with value types such as Array, Dictionary and String to defer the actual copying of data until it is modified. This helps in minimizing unnecessary data copying and thus improve performance.

How "copy on write" works ?

When you assign or pass a value type to another variable or function. Swift doesn't immediately creates the copy of data. Instead it shares the same underlying storage until the copy is modified.

Note: When you have an array of custom structs, the array itself will benefit from COW.

Why Extension cannot contains stored properties ?

This design decision is based on few key reasons.

1. Memory Layout and Instance size:

The memory layout of a type is determined at complie time based on its properties.

Allowing stored properties in extension would complicate this process, as compiler would need to accounts additional properties that might be added in extension and recompile the type.

If extension could add stored properties, the compiler needs to dynamically adjust the memory layout of a type, which could lead to performance overhead.

2. Initilization Complexity

Initialization logic becomes more complex if stored properties are allowed in extensions. The complier needs to ensure that all the stored properties are properly initialized even those are added in extensions.

3. Definition

Extensions are intended to extend existing types with new functionality rather than altering the fundamental structure.


Observation:

  1. Frameworks provided by Apple like Foundation, UIKit, CoreGraphics etc is precomplied. They are dynamically linked at runtime rather than compiled being compiled with our source code.
  2. Memory layout of a type, including its size (calculated from properties) is determined at compile time.
    This means the exact memory structure is known and fixed when code is compiled.
    For the layout and size the struct and classes includes all the stored properites while classes also include additional meta data for object management. Enums layout depends upon cases and associated values.

Reference:

  1. ChatGPT
  2. Reddit

Print Value type address

func printValueTypeAddress(value: UnsafeRawPointer) {
    let bitPattern = Int(bitPattern: value)
    print(NSString(format: "%p", bitPattern))
}

Print Reference type address

func printReferenceTypeAddress(reference: AnyObject) {
    print(Unmanaged.passUnretained(reference).toOpaque())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment