0
0
Blockchain / Solidityprogramming~5 mins

Visibility modifiers (public, private, internal, external) in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Visibility modifiers (public, private, internal, external)
O(n)
Understanding Time Complexity

When working with blockchain smart contracts, functions have visibility modifiers that control who can call them.

We want to understand how these modifiers affect the number of operations when functions are called.

Scenario Under Consideration

Analyze the time complexity of calling functions with different visibility modifiers.


contract Example {
    uint data;

    function setDataPublic(uint x) public {
        data = x;
    }

    function setDataPrivate(uint x) private {
        data = x;
    }

    function callPrivate(uint x) public {
        setDataPrivate(x);
    }
}
    

This contract has functions with public and private visibility and shows calling a private function internally.

Identify Repeating Operations

Look for repeated function calls or loops that affect execution time.

  • Primary operation: Calling functions with different visibility.
  • How many times: Each function call happens once per external or internal call.
How Execution Grows With Input

The number of operations grows directly with how many times functions are called.

Input Size (n)Approx. Operations
10 calls10 function executions
100 calls100 function executions
1000 calls1000 function executions

Pattern observation: Each call adds a fixed amount of work, so total work grows linearly with calls.

Final Time Complexity

Time Complexity: O(n)

This means the total work grows in direct proportion to the number of function calls made.

Common Mistake

[X] Wrong: "Private functions run faster or cost less time than public ones because they are hidden."

[OK] Correct: Visibility controls who can call the function, but the time to execute the function itself is about what the code does, not its visibility.

Interview Connect

Understanding how visibility affects function calls helps you reason about contract design and performance in real blockchain projects.

Self-Check

"What if a public function calls an external function multiple times inside a loop? How would the time complexity change?"