Static vs non-static behavior in Java - Performance Comparison
We want to see how static and non-static parts of Java code affect how long it takes to run.
How does using static or non-static change the work done as input grows?
Analyze the time complexity of the following code snippet.
public class Example {
static int staticCounter = 0;
int instanceCounter = 0;
public static void staticMethod(int n) {
for (int i = 0; i < n; i++) {
staticCounter++;
}
}
public void nonStaticMethod(int n) {
for (int i = 0; i < n; i++) {
instanceCounter++;
}
}
}
This code has a static method and a non-static method, each looping n times to update counters.
Look at the loops that repeat work.
- Primary operation: The for-loops in both methods that run n times.
- How many times: Each loop runs exactly n times, increasing counters.
As n grows, the number of times the loop runs grows the same way for both methods.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The work grows directly with n, whether static or not.
Time Complexity: O(n)
This means the time to run grows in a straight line as n gets bigger, for both static and non-static methods.
[X] Wrong: "Static methods always run faster or take less time than non-static methods."
[OK] Correct: The time depends on what the method does, not just if it is static. Both methods here do the same loop work, so they take similar time.
Understanding how static and non-static code runs helps you explain performance clearly and shows you know how Java works under the hood.
"What if the static method called the non-static method inside its loop? How would the time complexity change?"
