Int, Double, Float number types in Swift - Time & Space 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.
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 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.
Each time we increase the count, the loop runs more times, doing more additions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 30 additions (10 for each type) |
| 100 | 300 additions |
| 1000 | 3000 additions |
Pattern observation: The number of operations grows directly with the input size; if you double the input, the work doubles.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items you add.
[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.
Understanding how number types affect performance helps you write clear and efficient code, a skill that shows you think about both correctness and speed.
"What if we replaced the for-loop with a recursive function doing the same additions? How would the time complexity change?"