0
0
Blockchain / Solidityprogramming~5 mins

Yield farming concepts in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Yield farming concepts
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of farmers increases, the number of balance updates grows at the same rate.

Input Size (n)Approx. Operations
1010 balance updates
100100 balance updates
10001000 balance updates

Pattern observation: The work grows directly with the number of farmers, so doubling farmers doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to distribute rewards grows linearly with the number of farmers.

Common Mistake

[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.

Interview Connect

Understanding how loops affect execution time helps you explain how smart contracts handle many users efficiently and why gas costs increase with more participants.

Self-Check

"What if the contract used a mapping to track rewards and updated balances only when farmers claim them? How would the time complexity change?"