Reputation: 1315
I am not too familiar with Java. I have the following question. I have seen similar posts on SO on this. What I am asking may be a bit different.
If I have the following situation
public class A {
public static void myMethod () {
// Does a whole lot of things including calls to DB
}
}
vs
public class A {
public void myMethod () {
// Does a whole lot of things including calls to DB
}
}
// In some other class
public void caller () {
A.myMethod (); vs new A().myMethod();
}
Reason I am looking at the non-static method is to ensure data is not shared between instances.
If the caller () method is being called often, would there be a performance cost because of the instantiation/class loading followed by the call to non-static method?
Upvotes: 0
Views: 601
Reputation: 102814
How often?
Unless you answer '5 billion times, every second', the answer is simple:
No, object creation has absolutely no effect whatsoever on performance.
You write code that is clean. Which is defined as: Easy to read, hard to misunderstand, easy to test, easy to modify in the face of changing requirements.
That is how you get to fast code. The system tends to spend 99% of the resources on 1% of the code. Therefore, optimizing that 1% is the only thing that matters. However, it's hard to pre-guess what the 1% will be (hence, you never ever mess with performance optimizations unless you first run a profiler so you know what matters). Generally optimizing that 1% requires changing how it works, which in turn requires changes to code that 'surrounds' your 1% (the code that calls it, and the code that is called by it / processes with it returns). This is easy if you write clean code, and hard if you micro-optimize for pointless reasons.
Hence, clean code is objectively faster.
If you think making an instance is better here (And it certainly is!), then do that.
Upvotes: 3