Contract inheritance in Blockchain / Solidity - Time & Space 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.
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.
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.
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 contract | 1 step to execute function |
| 5 contracts | 1 step to execute function |
| 10 contracts | 1 step to execute function |
Pattern observation: The work to execute a function does not grow with the number of inherited contracts.
Time Complexity: O(1)
This means the time to find and run a function remains constant regardless of how many contracts are inherited.
[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.
Understanding how contract inheritance affects execution helps you write efficient blockchain code and explain your design choices clearly.
"What if we used multiple inheritance with several contracts at the same level? How would the time complexity change?"