Virtual and override keywords in Blockchain / Solidity - Time & Space 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.
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 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.
Calling a virtual or overridden function costs about the same regardless of contract size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 function call |
| 100 | 1 function call |
| 1000 | 1 function call |
Pattern observation: The cost stays constant no matter how many contracts or overrides exist.
Time Complexity: O(1)
This means calling a virtual or overridden function takes the same time no matter how many contracts are involved.
[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.
Understanding how virtual and override keywords affect function call cost shows you know how smart contracts manage inheritance efficiently.
"What if the overridden function called another virtual function inside it? How would that affect the time complexity?"