0
0
Blockchain / Solidityprogramming~5 mins

Constructor function in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Constructor function
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

Each extra number means one more step in the loop.

Input Size (n)Approx. Operations
1010 steps
100100 steps
10001000 steps

Pattern observation: The time grows directly with the number of items; double the items, double the steps.

Final Time Complexity

Time Complexity: O(n)

This means the constructor takes longer in a straight line as you add more numbers.

Common Mistake

[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.

Interview Connect

Understanding how constructor time grows helps you write efficient contracts and explain your code clearly in real projects.

Self-Check

"What if we replaced the loop with a fixed number of assignments? How would the time complexity change?"