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?
CodePudding user response:
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.
CodePudding user response:
Besides rzswitserloot's great answer regarding what good code is, you should also think about the possible scenarios of creating new instances that concurrently access an external DB: Does it have a limit of active connections? What if 1000 instances of A
try to simultaneously access the DB?
If you don't want data related to that function to be shared among other instances, you could just parametrize the static function with the variables to be used inside.
With those two points in mind, you could, as an alternative, reach to:
public class A {
public static syncrhonized void myMethod (int x, String s, Object o) {
// Does a whole lot of things including calls to DB
}
}
Two advantages here:
- No need to create multiple instances just because of different data values for the function
myMethod
. - You synchronize the calls to the BD, so that just one thread accesses it at a time.
As said, this may not be required in your project, but just wanted to offer an alternative here.