Data types (uint, int, bool, address, string) in Blockchain / Solidity - Time & Space 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.
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 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.
As the string gets longer, counting its length takes more steps.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps to count bytes |
| 100 | 100 steps to count bytes |
| 1000 | 1000 steps to count bytes |
Pattern observation: The time grows directly with the string length.
Time Complexity: O(n)
This means the time to get the string length grows linearly with the string size.
[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.
Understanding how data types affect operation time helps you write efficient smart contracts and explain your reasoning clearly.
"What if we changed the string to a fixed-size byte array? How would the time complexity change?"