0
0
Blockchain / Solidityprogramming~5 mins

Multiple inheritance in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Multiple inheritance
O(n)
Understanding Time Complexity

When using multiple inheritance in blockchain smart contracts, it's important to understand how the execution time grows as contracts combine features from several parents.

We want to know how the cost changes when calling functions inherited from multiple contracts.

Scenario Under Consideration

Analyze the time complexity of the following Solidity code snippet.


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

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

contract C is A, B {
    function combined() public pure returns (uint) {
        return foo() + bar();
    }
}
    

This code shows a contract C inheriting from two contracts A and B, then calling functions from both.

Identify Repeating Operations

Look for repeated actions that affect execution time.

  • Primary operation: Calling inherited functions foo() and bar().
  • How many times: Each function is called once per combined() call.
How Execution Grows With Input

As the number of inherited contracts grows, the number of function calls inside combined() can increase.

Number of Parents (n)Approx. Operations
22 function calls
55 function calls
1010 function calls

Pattern observation: Execution time grows linearly with the number of inherited contracts called.

Final Time Complexity

Time Complexity: O(n)

This means the execution time increases in a straight line as you add more inherited contracts with functions to call.

Common Mistake

[X] Wrong: "Multiple inheritance makes execution time jump exponentially because of all the parents combined."

[OK] Correct: Each inherited function is called separately, so the time adds up linearly, not exponentially.

Interview Connect

Understanding how multiple inheritance affects execution time helps you write efficient smart contracts and explain your design choices clearly.

Self-Check

"What if the inherited functions called inside combined() themselves call other inherited functions? How would the time complexity change?"