Accname
2D-Graphics enthusiast
- Reaction score
- 1,462
Hi guys, just wanted to share this with you.
Lets say I have a class like this:
I was curious which was faster:
or
So I made a simple test:
And I let the above code run 100 times.
The result was baffling, the get-method was actually faster then accessing the value directly.
I always thought it would be the other way around.
Well, it probably is the other way around for languages like C++ and alike, but apparently its faster in Java to call a method.
Just loling. I wanted to share this with you guys.
Lets say I have a class like this:
Code:
public class CrazyClass {
public int x;
public int getX() {
return x;
}
}
Code:
new CrazyClass().x;
Code:
new CrazyClass().getX();
So I made a simple test:
Code:
int runCount = 1000000;
int sum = 0;
CrazyClass c = new CrazyClass();
long timestamp = System.nanoTime();
for (int i = 0; i < runCount; i++) {
sum += c.x;
}
System.out.println("Time since: "+(System.nanoTime() - timestamp)+" Nanoseconds.");
sum = 0;
timestamp = System.nanoTime();
for (int i = 0; i < runCount; i++) {
sum += c.getX();
}
System.out.println("Time since: "+(System.nanoTime() - timestamp)+" Nanoseconds.");
}
The result was baffling, the get-method was actually faster then accessing the value directly.
I always thought it would be the other way around.
Well, it probably is the other way around for languages like C++ and alike, but apparently its faster in Java to call a method.
Just loling. I wanted to share this with you guys.