0
0
Swiftprogramming~5 mins

Int, Double, Float number types in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Int, Double, Float number types
O(n)
Understanding Time Complexity

Let's explore how operations with Int, Double, and Float types affect the time it takes for a program to run.

We want to know how the choice of these number types changes the speed when doing calculations.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    func sumNumbers(count: Int) {
      var totalInt = 0
      var totalDouble = 0.0
      var totalFloat: Float = 0.0
      for i in 1...count {
        totalInt += i
        totalDouble += Double(i)
        totalFloat += Float(i)
      }
      print(totalInt, totalDouble, totalFloat)
    }
    

This code adds numbers from 1 up to a given count using Int, Double, and Float types.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single for-loop that runs additions for each number.
  • How many times: The loop runs exactly count times.
How Execution Grows With Input

Each time we increase the count, the loop runs more times, doing more additions.

Input Size (n)Approx. Operations
1030 additions (10 for each type)
100300 additions
10003000 additions

Pattern observation: The number of operations grows directly with the input size; if you double the input, the work doubles.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of items you add.

Common Mistake

[X] Wrong: "Using Double or Float makes the code slower because they are decimal types."

[OK] Correct: The time to add Int, Double, or Float is very similar because the processor handles these operations efficiently; the main factor is how many times you do the addition, not the type.

Interview Connect

Understanding how number types affect performance helps you write clear and efficient code, a skill that shows you think about both correctness and speed.

Self-Check

"What if we replaced the for-loop with a recursive function doing the same additions? How would the time complexity change?"