Constructor function in Blockchain / Solidity - Time & Space Complexity
When we create a new blockchain contract, the constructor function runs once to set up initial values.
We want to know how the time it takes to run the constructor changes as we add more data.
Analyze the time complexity of the following constructor function.
contract SimpleContract {
uint[] public numbers;
constructor(uint[] memory initialNumbers) {
for (uint i = 0; i < initialNumbers.length; i++) {
numbers.push(initialNumbers[i]);
}
}
}
This constructor copies each number from the input list into the contract's storage one by one.
Look for loops or repeated steps.
- Primary operation: The for-loop that runs once for each number in the input array.
- How many times: Exactly as many times as the length of the input array.
Each extra number means one more step in the loop.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: The time grows directly with the number of items; double the items, double the steps.
Time Complexity: O(n)
This means the constructor takes longer in a straight line as you add more numbers.
[X] Wrong: "The constructor runs in constant time no matter how many numbers we add."
[OK] Correct: Because the constructor loops through each number, more numbers mean more steps, so time grows with input size.
Understanding how constructor time grows helps you write efficient contracts and explain your code clearly in real projects.
"What if we replaced the loop with a fixed number of assignments? How would the time complexity change?"