Checker InefficientConstruction   as of Julia version 2.4 (built on 23 Oct 2017)

belongs to group Basic

Identify inefficient constructions when static constants or factories can be used


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.

Examples


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.java:6: [InefficientConstruction: InefficientConstructionWarning] Inefficient instantiation of java.lang.String: can you use a string literal instead?
InefficientConstruction.java:8: [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);
  }