Constants and immutables in Blockchain / Solidity - Time & Space Complexity
When using constants and immutables in blockchain code, it's important to see how they affect the speed of the program.
We want to know if using these fixed values changes how long the code takes as input grows.
Analyze the time complexity of the following code snippet.
contract Example {
uint256 public constant FIXED_VALUE = 100;
uint256 public immutable creationTime;
constructor() {
creationTime = block.timestamp;
}
function multiply(uint256 input) public pure returns (uint256) {
return input * FIXED_VALUE;
}
}
This code defines a constant and an immutable value, then uses the constant in a simple multiplication function.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single multiplication operation in the multiply function.
- How many times: Once per function call, no loops or repeated steps inside.
The execution time of multiply does not grow with input size because it only does one multiplication each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 multiplication |
| 100 | 1 multiplication |
| 1000 | 1 multiplication |
Pattern observation: The number of operations per function call remains constant (1 multiplication), regardless of input size.
Time Complexity: O(1)
This means each call to the function takes the same small amount of time, no matter the input size.
[X] Wrong: "Using constants or immutables makes the function slower because they add extra steps."
[OK] Correct: Constants and immutables are fixed values stored efficiently, so accessing them does not slow down the function.
Understanding how constants and immutables affect time helps you write clear and efficient blockchain code, a skill valued in real projects and interviews.
"What if the multiply function used a loop to multiply the input by the constant multiple times? How would the time complexity change?"