0

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?

user2125853
  • 1,265
  • 4
  • 13
  • 23
  • 2
    Yes, creating an object needs more time than not creating an object, obviously. Why do you ask? What is the actual question you want to ask or what is the problem you have? – Progman Oct 12 '22 at 19:13
  • I'd offer up a third option: you'd have a field `A myDB = new A();`, and then `#caller` can do `myDB.myMethod();`. The number of instances made is relatively trivial compared to the IO expense of the DB operations. Overall though, I'd question what state is really being shared between instances of `A` such that they would even need separation. Be wary of some of the design pitfalls as well with baking in all of your DB operations into a static utility class – Rogue Oct 12 '22 at 19:13

1 Answers1

3

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.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72