0
0
Swiftprogramming~5 mins

Why structs are preferred in Swift - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why structs are preferred in Swift
O(n)
Understanding Time Complexity

When we choose between structs and classes in Swift, it helps to understand how their performance changes as data grows.

We want to see how the cost of using structs scales compared to classes.

Scenario Under Consideration

Analyze the time complexity of copying a struct versus a class instance.


struct Point {
  var x: Int
  var y: Int
}

let p1 = Point(x: 10, y: 20)
let p2 = p1 // Copy of struct

class Circle {
  var radius: Int
  init(radius: Int) { self.radius = radius }
}

let c1 = Circle(radius: 5)
let c2 = c1 // Reference to same class instance

This code shows copying a struct creates a new copy, while copying a class just copies a reference.

Identify Repeating Operations

Look at what happens when copying data:

  • Primary operation: Copying all stored properties in the struct.
  • How many times: Once per copy operation, proportional to the size of the struct.
How Execution Grows With Input

As the struct grows larger, copying takes more time because all data is duplicated.

Input Size (n)Approx. Operations
1010 copies of properties
100100 copies of properties
10001000 copies of properties

Pattern observation: Copying time grows linearly with the size of the struct.

Final Time Complexity

Time Complexity: O(n)

This means copying a struct takes time proportional to its size, growing steadily as the data grows.

Common Mistake

[X] Wrong: "Copying a struct is always slower than using a class because it duplicates data every time."

[OK] Correct: For small structs, copying is very fast and often cheaper than managing references and memory for classes.

Interview Connect

Understanding how structs copy data helps you explain why Swift prefers structs for safety and performance in many cases.

Self-Check

"What if the struct contains a large array? How would copying affect time complexity then?"