Answer the question
In order to leave comments, you need to log in
For Java lovers?
I never really liked to move code into static methods, I usually did it, if not without it. And then I thought about it and I just can’t find the right answer to what seems to me a fairly easy question.
Does it make sense (in terms of resources, performance or?) in the transformation:
public class A
{
private final int a;
private final Map<Integer, Integer> map;
public A(int a)
{
this.a = a;
this.map = new HashMap<Integer, Integer>();
}
public int calcSomthing()
{
int b = 0;
for (int i : map.values())
if (i == a)
b++;
return b;
}
}
public class A
{
// ...
public int getA()
{
return a;
}
public Collection<Integer> getValues()
{
return map.values();
}
public static int calcSomthing(A obj)
{
int b = 0;
for (int i : obj.getValues())
if (i == obj.getA())
b++;
return b;
}
}
Answer the question
In order to leave comments, you need to log in
Answer: No, such transformations are not worth doing. The code generated by the JIT compiler for both options will be almost the same, but the first option looks clearer and ideologically correct. Do not bother yourself with the fact that calling a static method is supposedly faster than a virtual one. In fact, due to dynamic devirtualization, the JVM will be able to call the method directly, bypassing the vtable. Moreover, in some cases, calling a static method can be even worse due to the class initialization barrier. In general, write what is best in terms of OOP architecture and concepts.
readability and convertibility of the code is more important than the benefits of a few commands
I highly doubt there will be any difference. Passing an object explicitly as a parameter or implicitly as this does not affect performance.
For a 100% guarantee, you need to conduct an investigative experiment or arm yourself with a disassembler.
I thought about it and came to the conclusion that I was wrong. The difference may be, because if the method is virtual, then polymorphism is possible, i.e. you need to find which method to call. In the case of a static method, everything is already known at the compilation stage, so no additional runtime processing is needed. Those. in general, other things being equal, a static method will be faster.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question