0
0
Blockchain / Solidityprogramming~5 mins

Virtual and override keywords in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Virtual and override keywords
O(1)
Understanding Time Complexity

When using virtual and override keywords in blockchain smart contracts, it's important to understand how they affect the speed of function calls.

We want to know how the cost of calling these functions changes as the contract grows.

Scenario Under Consideration

Analyze the time complexity of the following Solidity code snippet.


contract Base {
    function foo() public virtual returns (uint) {
        return 1;
    }
}

contract Derived is Base {
    function foo() public override returns (uint) {
        return 2;
    }
}
    

This code shows a base contract with a virtual function and a derived contract that overrides it.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the overridden function.
  • How many times: Each call executes once, no loops or recursion involved.
How Execution Grows With Input

Calling a virtual or overridden function costs about the same regardless of contract size.

Input Size (n)Approx. Operations
101 function call
1001 function call
10001 function call

Pattern observation: The cost stays constant no matter how many contracts or overrides exist.

Final Time Complexity

Time Complexity: O(1)

This means calling a virtual or overridden function takes the same time no matter how many contracts are involved.

Common Mistake

[X] Wrong: "Overriding functions makes calls slower as more contracts inherit."

[OK] Correct: The call uses a fixed lookup, so the time does not grow with the number of contracts.

Interview Connect

Understanding how virtual and override keywords affect function call cost shows you know how smart contracts manage inheritance efficiently.

Self-Check

"What if the overridden function called another virtual function inside it? How would that affect the time complexity?"