0
0
Blockchain / Solidityprogramming~5 mins

Constants and immutables in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Constants and immutables
O(1)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

The execution time of multiply does not grow with input size because it only does one multiplication each time.

Input Size (n)Approx. Operations
101 multiplication
1001 multiplication
10001 multiplication

Pattern observation: The number of operations per function call remains constant (1 multiplication), regardless of input size.

Final Time Complexity

Time Complexity: O(1)

This means each call to the function takes the same small amount of time, no matter the input size.

Common Mistake

[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.

Interview Connect

Understanding how constants and immutables affect time helps you write clear and efficient blockchain code, a skill valued in real projects and interviews.

Self-Check

"What if the multiply function used a loop to multiply the input by the constant multiple times? How would the time complexity change?"