0
0
Blockchain / Solidityprogramming~5 mins

Why inheritance promotes code reuse in Blockchain / Solidity - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why inheritance promotes code reuse
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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.

Identify Repeating Operations

Look for repeated actions that affect execution time.

  • Primary operation: Calling baseFunction inside derivedFunction.
  • How many times: Each call to derivedFunction calls baseFunction once.
How Execution Grows With Input

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
11 function call
1010 function calls
100100 function calls

Pattern observation: The work grows linearly as you reuse more functions through inheritance.

Final Time Complexity

Time Complexity: O(n)

This means the execution time grows in a straight line with the number of inherited functions you call.

Common Mistake

[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.

Interview Connect

Understanding how inheritance affects execution helps you write smart contracts that reuse code without surprises in performance.

Self-Check

What if we changed inherited functions to call each other recursively? How would the time complexity change?