0
0
Blockchain / Solidityprogramming~5 mins

Contract inheritance in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Contract inheritance
O(1)
Understanding Time Complexity

When using contract inheritance in blockchain, it's important to know how the execution time changes as contracts grow.

We want to see how adding inherited contracts affects the work the blockchain does.

Scenario Under Consideration

Analyze the time complexity of the following Solidity contract inheritance example.

pragma solidity ^0.8.0;

contract A {
    function foo() public pure returns (uint) {
        return 1;
    }
}

contract B is A {
    function bar() public pure returns (uint) {
        return 2;
    }
}

contract C is B {
    function baz() public pure returns (uint) {
        return 3;
    }
}

This code shows three contracts where each one inherits from the previous, adding new functions.

Identify Repeating Operations

Look for repeated actions that affect execution time.

  • Primary operation: Calling functions from inherited contracts.
  • How many times: Each function call runs once, and the function to call is determined at compile time, so no runtime chain checking is needed.
How Execution Grows With Input

As more contracts are inherited, the system does not check more places at runtime to find functions because the function calls are resolved at compile time.

Input Size (n)Approx. Operations
1 contract1 step to execute function
5 contracts1 step to execute function
10 contracts1 step to execute function

Pattern observation: The work to execute a function does not grow with the number of inherited contracts.

Final Time Complexity

Time Complexity: O(1)

This means the time to find and run a function remains constant regardless of how many contracts are inherited.

Common Mistake

[X] Wrong: "Inheritance does not affect execution time because functions are just copied over."

[OK] Correct: Actually, this is correct: function calls are resolved at compile time, so inheritance does not add runtime overhead in finding functions.

Interview Connect

Understanding how contract inheritance affects execution helps you write efficient blockchain code and explain your design choices clearly.

Self-Check

"What if we used multiple inheritance with several contracts at the same level? How would the time complexity change?"