Interfaces in Blockchain / Solidity - Time & Space Complexity
When working with interfaces in blockchain, it's important to see how the code runs as input grows.
We want to know how the time to execute changes when using interfaces.
Analyze the time complexity of the following code snippet.
interface IToken {
function balanceOf(address owner) external view returns (uint);
}
contract Wallet {
IToken token;
address[] owners;
function totalBalance() public view returns (uint) {
uint total = 0;
for (uint i = 0; i < owners.length; i++) {
total += token.balanceOf(owners[i]);
}
return total;
}
}
This code defines an interface to check token balances and sums balances for a list of owners.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that calls
balanceOffor each owner. - How many times: Once for each owner in the
ownersarray.
As the number of owners grows, the total calls to balanceOf grow the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to balanceOf |
| 100 | 100 calls to balanceOf |
| 1000 | 1000 calls to balanceOf |
Pattern observation: The work grows directly with the number of owners.
Time Complexity: O(n)
This means the time to run grows in a straight line as the number of owners increases.
[X] Wrong: "Using an interface makes the code run instantly regardless of input size."
[OK] Correct: Calling interface functions still takes time for each call, so more owners mean more calls and more time.
Understanding how interface calls scale helps you write efficient blockchain contracts and explain your reasoning clearly.
What if we changed the owners array to a mapping and tried to sum balances? How would the time complexity change?