Ethereum Virtual Machine (EVM) in Blockchain / Solidity - Time & Space Complexity
When running code on the Ethereum Virtual Machine (EVM), it is important to understand how the time it takes grows as the input gets bigger.
We want to know how the number of steps changes when the data or instructions increase.
Analyze the time complexity of the following EVM bytecode loop.
// Pseudocode for EVM loop
for (uint i = 0; i < n; i++) {
sum += data[i];
}
This code sums up values from an array of size n by looping through each element once.
Look for repeated actions that take time.
- Primary operation: Looping through each element of the array.
- How many times: Exactly n times, once per element.
As the array size grows, the number of steps grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: The steps increase directly with the input size. Double the input, double the steps.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the size of the input.
[X] Wrong: "The loop runs in constant time because it just adds numbers."
[OK] Correct: Even though adding is simple, the loop runs once for each item, so more items mean more steps.
Understanding how loops affect execution time in the EVM helps you write efficient smart contracts and explain your code clearly in conversations.
"What if we replaced the loop with a recursive function that sums the array? How would the time complexity change?"