0
0
Blockchain / Solidityprogramming~5 mins

Data types (uint, int, bool, address, string) in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Data types (uint, int, bool, address, string)
O(n)
Understanding Time Complexity

When working with blockchain data types, it's important to know how operations on them grow as data size changes.

We want to see how the time to handle these types changes when the input gets bigger.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


contract Example {
    string public name;
    uint[] public numbers;

    function addNumber(uint num) public {
        numbers.push(num);
    }

    function getNameLength() public view returns (uint) {
        return bytes(name).length;
    }
}
    

This code stores a string and a list of numbers, adds numbers to the list, and gets the length of the string.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Accessing the length of the string by converting it to bytes.
  • How many times: The length operation checks each byte once, so it depends on the string size.
How Execution Grows With Input

As the string gets longer, counting its length takes more steps.

Input Size (n)Approx. Operations
1010 steps to count bytes
100100 steps to count bytes
10001000 steps to count bytes

Pattern observation: The time grows directly with the string length.

Final Time Complexity

Time Complexity: O(n)

This means the time to get the string length grows linearly with the string size.

Common Mistake

[X] Wrong: "Getting the length of a string is always instant and does not depend on size."

[OK] Correct: In blockchain, strings are stored as byte arrays, so counting length requires checking each byte, which takes more time for longer strings.

Interview Connect

Understanding how data types affect operation time helps you write efficient smart contracts and explain your reasoning clearly.

Self-Check

"What if we changed the string to a fixed-size byte array? How would the time complexity change?"