0
0
Swiftprogramming~5 mins

Comparing structs vs classes decision in Swift - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Comparing structs vs classes decision
O(n)
Understanding Time Complexity

When choosing between structs and classes in Swift, it's important to understand how their operations grow as your data size increases.

We want to see how the time cost changes when working with many instances of each type.

Scenario Under Consideration

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


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

class PointClass {
  var x: Int
  var y: Int
  init(x: Int, y: Int) {
    self.x = x
    self.y = y
  }
}

// Creating and copying 1000 instances
var structPoints = [PointStruct]()
var classPoints = [PointClass]()
for i in 0..<1000 {
  structPoints.append(PointStruct(x: i, y: i))
  classPoints.append(PointClass(x: i, y: i))
}

// Copying struct array
let copiedStructPoints = structPoints

// Copying class array
let copiedClassPoints = classPoints

This code creates arrays of structs and classes, then copies the arrays to compare how copying behaves.

Identify Repeating Operations

Look for loops and copying actions that repeat work.

  • Primary operation: Loop creating 1000 instances of structs and classes.
  • How many times: 1000 times for creation; copying arrays happens once but behaves differently.
How Execution Grows With Input

Creating instances grows linearly with the number of items.

Input Size (n)Approx. Operations
1010 creations
100100 creations
10001000 creations

Copying struct arrays duplicates all data, so operations grow with n. Copying class arrays only copies references, so it stays almost constant.

Final Time Complexity

Time Complexity: O(n)

This means the time to create or copy grows directly with the number of items.

Common Mistake

[X] Wrong: "Copying a class array duplicates all objects like structs."

[OK] Correct: Copying a class array only copies references, not the objects themselves, so it is much faster than copying structs.

Interview Connect

Understanding how structs and classes behave with copying helps you explain performance choices clearly and confidently in real projects.

Self-Check

What if we changed the struct to contain a large array? How would copying the struct array affect time complexity?