Search code examples
javaperformancecdiweld

Performance: Utility class vs. CDI bean


I want to externalize commonly used applicationlogic into a "utility class" called Helper. The applicationlogic needs other CDI beans to work.

Two possibilities:

a)

@SessionScoped
class ControllerWithCdiBean {

  @Inject
  Helper helper;

  public void doIt() {
      Object result = helpder.calculate();
  }
}

@RequestScoped
class Helper{

  @Inject
  Service anyService;

  public Object calculate() {
     return anyService.calc();
  }
}

b)

@SessionScoped
class ControllerWithStaticCallsViaDeltaspike {

  public void doIt() {
      Object result = Helpder.calculate();
  }
}

class Helper{

  private static Service anyService = BeanProvider.getContextualReference(Service.class);

  public static Object calculate() {
     return anyService.calc();
  }

What about performance? Are there any notable differences? Both solutions are possible for me, is one solutions better than the other?

One disadvantage: Helpder gets initialized for every Request.


Solution

  • Mark your Helper class as @ApplicationScoped. With this, you will have a single instance per application context.

    Still, if it's just an utility class, it shouldn't be a managed bean at all. I would instead mark it as final, define a private constructor and mark all the methods as static. This is because since it's an utility class, it doesn't need to maintain any state.