Why inheritance promotes code reuse in Blockchain / Solidity - Performance Analysis
When using inheritance in blockchain smart contracts, we want to see how adding more inherited contracts affects the work the system does.
We ask: How does the execution time grow as we reuse more code through inheritance?
Analyze the time complexity of the following Solidity code snippet.
contract Base {
function baseFunction() public pure returns (uint) {
return 1;
}
}
contract Derived is Base {
function derivedFunction() public pure returns (uint) {
return baseFunction() + 1;
}
}
This code shows a contract Derived inheriting from Base, reusing baseFunction inside its own function.
Look for repeated actions that affect execution time.
- Primary operation: Calling
baseFunctioninsidederivedFunction. - How many times: Each call to
derivedFunctioncallsbaseFunctiononce.
As you add more inherited functions and call them, the total work grows with how many functions run.
| Input Size (number of inherited functions called) | Approx. Operations |
|---|---|
| 1 | 1 function call |
| 10 | 10 function calls |
| 100 | 100 function calls |
Pattern observation: The work grows linearly as you reuse more functions through inheritance.
Time Complexity: O(n)
This means the execution time grows in a straight line with the number of inherited functions you call.
[X] Wrong: "Inheritance makes the code run instantly with no extra cost."
[OK] Correct: Even though inheritance saves writing code again, each inherited function still runs when called, adding to execution time.
Understanding how inheritance affects execution helps you write smart contracts that reuse code without surprises in performance.
What if we changed inherited functions to call each other recursively? How would the time complexity change?