0
0
Swiftprogramming~5 mins

Why classes exist alongside structs in Swift - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why classes exist alongside structs
O(n)
Understanding Time Complexity

When we look at why Swift has both classes and structs, it helps to think about how their performance changes as we use them more.

We want to understand how the cost of using classes or structs grows when we work with many objects.

Scenario Under Consideration

Analyze the time complexity of creating and copying structs versus classes.


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

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

// Creating many instances
var points = [Point]()
var circles = [Circle]()
for i in 0..

This code creates many Point structs and Circle class instances, showing how they behave when copied or referenced.

Identify Repeating Operations

Look at what repeats as we create many objects.

  • Primary operation: Creating and storing each Point struct and Circle class instance.
  • How many times: Exactly n times, once per loop iteration.
How Execution Grows With Input

As n grows, the number of creations grows the same way.

Input Size (n)Approx. Operations
1010 creations of structs and classes
100100 creations of structs and classes
10001000 creations of structs and classes

Pattern observation: The work grows directly with n, doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to create and store these objects grows in a straight line with the number of items.

Common Mistake

[X] Wrong: "Classes and structs always have the same performance because they both hold data."

[OK] Correct: Structs copy all their data when assigned or passed, which can be costly for large data, while classes use references, so copying is cheaper but managing references adds overhead.

Interview Connect

Understanding why Swift has both classes and structs helps you explain design choices clearly and shows you know how performance can change with different data types.

Self-Check

"What if we changed the struct Point to have many properties or nested structs? How would the time complexity of copying change?"