ERC-721 NFT standard in Blockchain / Solidity - Time & Space Complexity
When working with ERC-721 NFTs, it's important to understand how the time to perform actions grows as the number of tokens increases.
We want to know how the cost of operations like transferring or checking ownership changes as more NFTs 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");
require(to != address(0), "Invalid address");
_approve(address(0), tokenId);
_owners[tokenId] = to;
_balances[from] -= 1;
_balances[to] += 1;
emit Transfer(from, to, tokenId);
}
This code transfers ownership of a single NFT from one address to another.
Look for loops or repeated steps that depend on input size.
- Primary operation: Accessing and updating ownership and balances for one token.
- How many times: Each transfer handles exactly one token, so operations happen once per call.
The work done for transferring one token stays the same no matter how many tokens exist.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 operation (one per token transfer) |
| 100 | 1 operation (still one per transfer) |
| 1000 | 1 operation (one per transfer) |
Pattern observation: The time per transfer does not increase as more tokens exist; it stays constant.
Time Complexity: O(1)
This means transferring a token takes the same amount of time no matter how many NFTs are in the contract.
[X] Wrong: "Transferring a token gets slower as more tokens exist because the contract must check all tokens."
[OK] Correct: The contract uses direct mappings to find owners, so it looks up only the specific token without scanning others.
Understanding how blockchain operations scale helps you explain gas costs and efficiency clearly, a useful skill for blockchain development roles.
"What if the contract stored all tokens owned by an address in an array and had to search it to find a token? How would the time complexity change?"