0
0
Blockchain / Solidityprogramming~5 mins

Factory pattern in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Factory pattern
O(n)
Understanding Time Complexity

When using the factory pattern in blockchain code, it's important to know how the time needed to create objects grows as we create more of them.

We want to understand how the cost changes when making many objects through the factory.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


contract TokenFactory {
    Token[] public tokens;

    function createToken(string memory name) public {
        Token newToken = new Token(name);
        tokens.push(newToken);
    }
}

contract Token {
    string public name;
    constructor(string memory _name) {
        name = _name;
    }
}
    

This code creates new Token contracts using a factory contract and stores them in an array.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating a new Token contract and adding it to the tokens array.
  • How many times: Once per call to createToken, repeated as many times as tokens are created.
How Execution Grows With Input

Each time we create a token, the factory does a fixed amount of work: deploy one Token and add it to the array.

Input Size (n)Approx. Operations
1010 token creations and 10 array insertions
100100 token creations and 100 array insertions
10001000 token creations and 1000 array insertions

Pattern observation: The work grows directly with the number of tokens created, increasing steadily.

Final Time Complexity

Time Complexity: O(n)

This means the time to create tokens grows linearly with how many tokens you make.

Common Mistake

[X] Wrong: "Creating many tokens at once is just as fast as creating one token."

[OK] Correct: Each token creation requires deploying a new contract and updating the array, so the total time adds up with each new token.

Interview Connect

Understanding how factory patterns scale helps you explain how smart contract deployments affect blockchain performance and costs.

Self-Check

"What if the factory stored tokens in a mapping instead of an array? How would the time complexity change?"