Yield farming concepts in Blockchain / Solidity - Time & Space Complexity
When working with yield farming smart contracts, it is important to understand how the time to process rewards grows as more users participate.
We want to know how the contract's execution time changes when the number of farmers increases.
Analyze the time complexity of the following code snippet.
function distributeRewards(address[] memory farmers, uint256 totalReward) public {
uint256 rewardPerFarmer = totalReward / farmers.length;
for (uint256 i = 0; i < farmers.length; i++) {
balances[farmers[i]] += rewardPerFarmer;
}
}
This function divides a total reward equally among all farmers by looping through each farmer and updating their balance.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of farmers to update balances.
- How many times: Once for each farmer in the array.
As the number of farmers increases, the number of balance updates grows at the same rate.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 balance updates |
| 100 | 100 balance updates |
| 1000 | 1000 balance updates |
Pattern observation: The work grows directly with the number of farmers, so doubling farmers doubles the work.
Time Complexity: O(n)
This means the time to distribute rewards grows linearly with the number of farmers.
[X] Wrong: "The reward distribution happens instantly no matter how many farmers there are."
[OK] Correct: Because the contract must update each farmer's balance one by one, more farmers mean more work and more time.
Understanding how loops affect execution time helps you explain how smart contracts handle many users efficiently and why gas costs increase with more participants.
"What if the contract used a mapping to track rewards and updated balances only when farmers claim them? How would the time complexity change?"