Reputation: 21150
I was wondering:
Let's say I have a class that uses static objects to do certain computations:
public class test {
static String test = "Hello World";
public static void main(String[] args)
{
System.out.println(staticMethod());
}
static String staticMethod()
{
return test;
}
}
Now would there be a difference in computation time if I would use another class like so:
public class test {
static String test = "Hello World";
public static void main(String[] args)
{
System.out.println(test2.staticMethod());
}
}
import static dataConnection.test.*;
public class test2 {
static String staticMethod()
{
return test;
}
}
Hence if I move the static method into a different class?
My theory would be that because Java passes pointers, there should be no difference. But doesn't the compiler have to dig through more code, hence the computation time will increase?
Upvotes: 1
Views: 93
Reputation: 8191
Using a static
method has a slightly less overhead due to the fact that you have guaranteed compile time binding. Static
method calls will create the bytecode
instruction invokestatic. ]
In practice, it won't make any difference. JVM may choose to optimize in ways that make static
calls faster for one method in a class, static
calls faster for another in another class. The root cause of performance hit which you experience is mainly due to Premature optimization.
Also note that old JVMs may/may not have optimization feature.
Upvotes: 1
Reputation: 328568
The compiler would have a bit more work but at runtime it will not make any difference. In particular, if that (short) method is run enough times it will be inlined so its original location is irrelevant.
Upvotes: 1
Reputation: 200138
But doesn't the compiler have to dig through more code, hence the computation time will increase?
You must mean compilation time. Computation happens at runtime and its performance has no correlation with the time it took to compile the computing code.
In other words: the location of a static method has no effect on performance.
Upvotes: 2