Software engineering principles - Time & Space Complexity
When we think about software engineering principles, we often focus on how they guide building good software. But it is also important to understand how following these principles affects the time it takes for software to run or grow.
We want to answer: How does the work needed change as the software or its input grows?
Analyze the time complexity of the following code snippet.
// Example: Simple function following single responsibility principle
function sumArray(numbers) {
let total = 0;
for (let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
return total;
}
This function adds all numbers in an array, showing a clear, focused task.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array once.
- How many times: Exactly as many times as there are items in the array.
As the array gets bigger, the function does more additions, one for each item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to complete the task grows in a straight line with the input size.
[X] Wrong: "Since the function has a loop, it must be slow or complicated."
[OK] Correct: A single loop that goes through data once is actually very efficient and simple. It grows steadily, not wildly.
Understanding how simple, clear principles like doing one thing well also help keep your code efficient is a valuable skill. It shows you can write code that is both easy to maintain and performs well as it grows.
"What if we changed the function to sum only even numbers in the array? How would the time complexity change?"