For expressions for transformation in Terraform - Time & Space Complexity
We want to understand how the time to run a Terraform for expression changes as the input list grows.
Specifically, how does the number of operations grow when transforming a list with a for expression?
Analyze the time complexity of this Terraform for expression.
locals {
input_list = [1, 2, 3, 4, 5]
output_list = [for item in local.input_list : item * 2]
}
This code takes each number in the input list and multiplies it by 2, creating a new list.
Look at what repeats as the input list grows.
- Primary operation: Multiplying each item by 2 (one operation per item).
- How many times: Once for each item in the input list.
As the input list gets bigger, the number of multiplications grows at the same rate.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 multiplications |
| 100 | 100 multiplications |
| 1000 | 1000 multiplications |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to complete the transformation grows in direct proportion to the input list size.
[X] Wrong: "The for expression runs in constant time no matter how big the list is."
[OK] Correct: Each item must be processed once, so more items mean more work and more time.
Understanding how simple transformations scale helps you reason about Terraform configurations and their efficiency in real projects.
"What if the for expression included a nested for expression inside it? How would the time complexity change?"