Checker InefficientConstruction

belongs to group Basic
Identify inefficient constructions when static constants or factories can be used

Frameworks supported by this checker

  • java up to 11
  • android up to API level 28

Warnings generated by this checker

  • InefficientBoxUnboxWarning: a box/unbox sequence can be simplified and made more efficient [ CWE227 ]
  • InefficientConstructionForGetClassWarning: a class is only instantiated to get its class tag, instead of using its name and the .class pseudo-field [ CWE227 ]
  • InefficientConstructionWarning: the construction of an object might be replaced by a literal or by a call to a factory method [ CWE400 ]
  • PassingEmptyArrayWarning: an empty array is passed to a method instead of an array of the proper size [ CWE227 ]

Options accepted by this checker

  • none

Annotations understood by this checker

  • @com.juliasoft.julia.checkers.inefficientConstruction.InefficientConstruction


It is often convenient to use a literal or a unique object instead of explicitly constructing new instances, when the same object is used many times, since distinct objects are created at each new statement, which affects the performance of the code. Moreover, objects used instead of literals are often short-lived and consequently must be claimed back from the garbage-collector.

Action: Use string literals instead of the creation of constant strings. Use factory methods or the automatic boxing mechanism instead of the instantiation of a primitive wrapper class.


Consider the following program:

import java.util.HashMap;
import java.util.Map;

public class InefficientConstruction {
  public static void foo() {
    String s = new String("hello");
    Map<Integer, String> map = new HashMap<Integer, String>();
    map.put(new Integer(13) , s);

This checker issues the following warnings: [InefficientConstruction: InefficientConstructionWarning] Inefficient instantiation of java.lang.String: can you use a string literal instead? [InefficientConstruction: InefficientConstructionWarning] Inefficient instantiation of java.lang.Integer: can you use a static constant, the automatic boxing mechanism or java.lang.Integer.valueOf(int) instead?

since the instantiation of the string can be replaced by the explicit use of a string literal. Moreover, the Integer object is recreated at each execution of method foo, while the use of the factory method Integer.valueOf(13) uses a cache to yield always the same object, at least for small values.

In this example, the programmer should modify the program as follows:

  public static void foo() {
    String s = "hello";
    Map<Integer, String> map = new HashMap<Integer, String>();
    map.put(Integer.valueOf(13), s);

The automatic boxing mechanism uses the same optimization, hence the same optimized code could also be written as

  public static void foo() {
    String s = "hello";
    Map<Integer, String> map = new HashMap<Integer, String>();
    map.put(13, s);