Reference vs pointer in C++ - Performance Comparison
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?
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.
Look for repeated actions that take time.
- Primary operation: Incrementing the integer value.
- How many times: Each function does this once per call.
Since each function just changes one number once, the work stays the same no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments if called 10 times |
| 100 | 100 increments if called 100 times |
| 1000 | 1000 increments if called 1000 times |
Pattern observation: The work grows directly with how many times you call the function.
Time Complexity: O(n)
This means the time grows in a straight line with the number of times you run the increment.
[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.
Understanding how references and pointers work helps you write clear and efficient code, a skill valued in many programming tasks.
"What if we passed the integer by value instead of by pointer or reference? How would the time complexity change?"