Abstract contracts in Blockchain / Solidity - Time & Space Complexity
When working with abstract contracts in blockchain, it's important to understand how the execution time grows as more contracts or functions are involved.
We want to know how the cost changes when calling or inheriting from abstract contracts.
Analyze the time complexity of the following Solidity abstract contract example.
abstract contract Base {
function calculate(uint n) public virtual returns (uint);
}
contract Derived is Base {
function calculate(uint n) public override returns (uint) {
uint sum = 0;
for (uint i = 0; i < n; i++) {
sum += i;
}
return sum;
}
}
This code defines an abstract contract with a function to calculate a value, and a derived contract that implements it by summing numbers up to n.
Look for loops or repeated steps that affect execution time.
- Primary operation: The for-loop inside the
calculatefunction. - How many times: It runs
ntimes, wherenis the input number.
As the input n grows, the loop runs more times, increasing the work done.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of operations grows directly with n. Double the input, double the work.
Time Complexity: O(n)
This means the time to run the function grows in a straight line with the input size.
[X] Wrong: "Abstract contracts add extra hidden loops that slow down execution significantly."
[OK] Correct: Abstract contracts only define function signatures; the actual work happens in the derived contract. The time depends on the implemented code, not the abstract definition.
Understanding how abstract contracts affect execution helps you write efficient smart contracts and explain your design choices clearly in interviews.
"What if the calculate function called another function inside the loop? How would that affect the time complexity?"