0
0
Blockchain / Solidityprogramming~5 mins

Reference types behavior in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Reference types behavior
O(n)
Understanding Time Complexity

When working with reference types in blockchain code, it's important to see how operations on these types affect performance.

We want to know how the time to run code changes as the size of the data referenced grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


struct Data {
  uint[] values;
}

function sumValues(Data storage data) public view returns (uint) {
  uint total = 0;
  for (uint i = 0; i < data.values.length; i++) {
    total += data.values[i];
  }
  return total;
}
    

This function sums all numbers stored in a dynamic array inside a struct passed by reference.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each element in the array data.values.
  • How many times: Once for every element in the array, so as many times as the array length.
How Execution Grows With Input

As the array gets bigger, the function does more additions, one per element.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the number of elements. Double the elements, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the function grows in a straight line with the size of the array.

Common Mistake

[X] Wrong: "Since the struct is passed by reference, the function runs in constant time regardless of array size."

[OK] Correct: Passing by reference avoids copying data but the loop still visits every element, so time grows with array length.

Interview Connect

Understanding how reference types affect time helps you explain performance clearly and shows you know how data size impacts blockchain functions.

Self-Check

"What if the function only summed the first 10 elements regardless of array size? How would the time complexity change?"