Contract structure and syntax in Blockchain / Solidity - Time & Space Complexity
When we write a contract, the way it is built affects how long it takes to run. We want to see how the contract's parts make the work grow as we add more data.
We ask: How does the contract's structure change the time it takes to do its job?
Analyze the time complexity of the following code snippet.
contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}
This contract stores a number and lets you set or get it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Simple assignment and retrieval of a single value.
- How many times: Each function runs once per call, no loops or repeated steps inside.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 simple assignment or retrieval |
| 100 | 1 simple assignment or retrieval |
| 1000 | 1 simple assignment or retrieval |
Pattern observation: Each call does the same small amount of work, no matter the input size.
Time Complexity: O(1)
This means the contract's functions take the same short time no matter how many times you use them or what number you store.
[X] Wrong: "Storing bigger numbers or calling the function more times makes it slower each time."
[OK] Correct: Each call only does one simple step, so the size of the number or how many times you call does not slow down each individual call.
Understanding how simple contract parts run helps you explain how your code behaves. This skill shows you know how to write efficient contracts that work well no matter the data.
"What if the contract stored a list of numbers instead of one? How would the time complexity change?"