ERC-721 implementation in Blockchain / Solidity - Time & Space Complexity
When working with ERC-721 tokens, it is important to understand how the time to execute key functions changes as the number of tokens grows.
We want to know how the cost of minting, transferring, or checking ownership changes when more tokens exist.
Analyze the time complexity of the following simplified ERC-721 transfer function.
function transferFrom(address from, address to, uint256 tokenId) public {
require(ownerOf[tokenId] == from, "Not owner");
ownerOf[tokenId] = to;
balances[from] -= 1;
balances[to] += 1;
}
This code transfers ownership of a single token from one address to another and updates balances.
Look for loops or repeated steps that depend on input size.
- Primary operation: Direct access and update of token ownership and balances.
- How many times: Each transfer handles exactly one token, so operations happen once per call.
The function always does a fixed number of steps regardless of how many tokens exist.
| Input Size (number of tokens) | Approx. Operations |
|---|---|
| 10 | 4 |
| 100 | 4 |
| 1000 | 4 |
Pattern observation: The number of operations stays the same no matter how many tokens exist.
Time Complexity: O(1)
This means the transfer function runs in constant time, doing the same amount of work no matter how many tokens there are.
[X] Wrong: "Transferring a token takes longer as more tokens exist because the contract must check all tokens."
[OK] Correct: The contract uses direct lookups by token ID, so it does not check all tokens. It only updates the specific token involved.
Understanding how smart contract functions scale with data size is a key skill. It shows you can write efficient blockchain code that saves gas and runs smoothly.
"What if the transfer function needed to check a list of all tokens owned by the sender? How would the time complexity change?"