0

Is there any difference between static method and normal method in class in performance in java 8?

class First {
    public static String methodStatic1() {
       //performance
    }
}

vs

class Second {
    public String method2() {
       //performance
    }
}
mkKowalka
  • 3
  • 1
  • 2
    have you checked? – Stultuske Jan 28 '19 at 14:23
  • Welcome to Stack Overflow! Please take the [tour] (you get a badge!), have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) The choice between a static or instance method is usually made for *other* reasons. It seems like this is [an X/Y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Are you running into some specific issue that's making you ask this question? If not, design your classes in the way that makes sense, and worry about performance if/when you have a performance problem to worry about. – T.J. Crowder Jan 28 '19 at 14:24
  • Yes, static seems to be faster, but maybe there is some optimalization done by `JIT` when I ran it. I want to get answer not by test, but by theory, why? – mkKowalka Jan 28 '19 at 14:25

1 Answers1

3

Addressing the performance aspect: it's cheaper not to have to create an instance of something pointlessly, but the difference is very likely to be completely irrelevant. Focusing on a clear design is much more likely to be important over time.

Utility methods are frequently static, and if all the methods within a class are static it may well be worth making the class final and including a private constructor to prevent instantation. Fundamentally, with utility classes which don't represent any real "thing" it doesn't make logical sense to construct an instance - so prevent it.

On the other hand, this does reduce flexibility: if any of these utility methods contain functionality which you may want to vary polymorphically (e.g. for testing purposes) then consider leaving them as instance methods - and try to extract some meaningful class name to represent the "thing" involved. (For example, a FooConverter makes sense to instantiate - a FooUtil doesn't.)

Bush
  • 261
  • 1
  • 11