To for Java?

0 like 0 dislike
2 views
Never really liked to make the code in static methods, doing it usually, if he does without it. And here thinking and I can't find the correct answer to, it seems to me, quite an easy question.


Does it make sense (for resources, or performance ?) in the transformation:

public class A { private final int a; private final Map map; public A(int a) { this.a = a; this.map = new HashMap(); } public int calcSomthing() { int b = 0; for (int i : map.values()) if (i == a) b++; return b; } }



in

public class A { // ... public int getA() { return a; } public Collection 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; } }



If we consider that objects a lot, say 50 thousand.


Or washed away will only if you have to make those methods static, which did not turn directly to class variables, and use only the other class methods?
by | 2 views

5 Answers

0 like 0 dislike
Answer: no, such changes to do not worth it. Generated JIT code for both options is almost the same, but the first option looks cleaner and ideologically correct. Do not bother the fact that calling a static method is supposedly faster virtual. In fact, due to the dynamic devirtualization JVM can call the method directly, bypassing the vtable. Moreover, in some cases, a call to a static method may be even worse due to the class initialization barrier. In General, write as is better from the point of view of architecture and OOP concepts.
by
0 like 0 dislike
readability and code Preobrazhensky important benefits in several commands
by
0 like 0 dislike
I seriously doubt that there's any difference in principle. Pass the object explicitly as a parameter or implicitly as this, the performance is not affected.
\r
For 100% guarantee it is necessary to conduct an investigative experiment or arm disassembler.
by
0 like 0 dislike
Thought about it and came to the conclusion that I'm wrong. The difference may be, because if the method is virtual, the possible polymorphism, i.e. we need to find which method to call. In the case of a static method, all known at compile time, so the extra runtime processing is not necessary. I.e. in the General case, other things being equal, a static method will be faster.
by
0 like 0 dislike
Here is another interesting read
The basic idea: static faster than private or public.
by

Related questions

0 like 0 dislike
1 answer
0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
0 like 0 dislike
4 answers
asked May 21, 2019 by black_niggar1998
0 like 0 dislike
1 answer
110,608 questions
257,186 answers
0 comments
28,783 users