0
0
C++programming~5 mins

Reference vs pointer in C++ - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Reference vs pointer
O(n)
Understanding Time Complexity

We want to see how using references or pointers affects the speed of a program.

How does the program's work change when we use one or the other?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


void incrementByPointer(int* ptr) {
    (*ptr)++;
}

void incrementByReference(int& ref) {
    ref++;
}

int main() {
    int a = 0;
    incrementByPointer(&a);
    incrementByReference(a);
    return 0;
}
    

This code shows two ways to increase a number: one uses a pointer, the other a reference.

Identify Repeating Operations

Look for repeated actions that take time.

  • Primary operation: Incrementing the integer value.
  • How many times: Each function does this once per call.
How Execution Grows With Input

Since each function just changes one number once, the work stays the same no matter the input size.

Input Size (n)Approx. Operations
1010 increments if called 10 times
100100 increments if called 100 times
10001000 increments if called 1000 times

Pattern observation: The work grows directly with how many times you call the function.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the number of times you run the increment.

Common Mistake

[X] Wrong: "Using pointers is always slower than references because of extra steps."

[OK] Correct: Both pointers and references usually compile to similar machine instructions, so their speed is nearly the same for simple operations.

Interview Connect

Understanding how references and pointers work helps you write clear and efficient code, a skill valued in many programming tasks.

Self-Check

"What if we passed the integer by value instead of by pointer or reference? How would the time complexity change?"