Multiple inheritance in Blockchain / Solidity - Time & Space 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.
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.
Look for repeated actions that affect execution time.
- Primary operation: Calling inherited functions
foo()andbar(). - How many times: Each function is called once per
combined()call.
As the number of inherited contracts grows, the number of function calls inside combined() can increase.
| Number of Parents (n) | Approx. Operations |
|---|---|
| 2 | 2 function calls |
| 5 | 5 function calls |
| 10 | 10 function calls |
Pattern observation: Execution time grows linearly with the number of inherited contracts called.
Time Complexity: O(n)
This means the execution time increases in a straight line as you add more inherited contracts with functions to call.
[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.
Understanding how multiple inheritance affects execution time helps you write efficient smart contracts and explain your design choices clearly.
"What if the inherited functions called inside combined() themselves call other inherited functions? How would the time complexity change?"