简体   繁体   中英

Better an helper class with only static methods or class instance with same helper methods

I have a question related to performance and how the compiler works in Java.

If I have a class with no state at all like

public class Helper {

  public String helperMethod(String text) {
     ....
     return value; 
  }
}

instead of doing

public class StaticHelper {

  public static String helperMethod(String text) {
     ....
     return value; 
  }
}

And then I do several call of type

new Helper().helperMethod("bla");

will the compiler somehow optimize the object creation or should I expect an overhead (minimal, I suppose) on the garbage collector and allocated memory?

Otherwise I should do StaticHelper.helperMethod("bla") , but this will prevent me to use a fluent interface, that I'd prefer.

There's no difference in these cases except the one moment. Nested class (static inner class) in Java doesn't have a reference to the Outer class, but the Inner class has a reference to the Outer. You can have problems with performance because JVM can't GC the Outer class if you have a reference to the Inner Class in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM