[Effective Java] Item 5: Avoid creating unnecessary objects

During the code review, maybe your boss will tell you that string creation should be placed outside the loop.

for(int i = 0; i < length; i++) {
    String s = new String(i);
}

why?

Because while looping, too many temporary objects are created. Each time through the loop, it is required new String()and assigned to a new object s. We can make the following improvements:

String s;
for(int i = 0; i < length; i++) {
    s = String.valueOf(i);
}

This avoids creating the object string each time through the loop s.

There Javaare a lot of other places in here with these little details:
1. Remember the case given in [Effective Java] Article 1: Consider using static factory methods instead of constructors 1Boolean ?

public static Boolean valueOf(boolean b) {
    return (b ? TRUE : FALSE);
}

Compared with the new Boolean(String s)constructor method, the sums valueOfreturned by the method are all built-in objects, not the same as the constructor method, which will create a new object every time it is called .TRUEFALSEBoolean

== Therefore, when you see that a class has both a constructor and a static constructor in the future, check the implementation of the static constructor, which may save a lot of resources. ==

  1. HashMapkeySetmethod that returns Mapall the forms in key. SetLooking at the code, you will find that what is here is Setactually AbstractMapa member variable in .
  2. JavaThere is also a situation in which unnecessary objects are implicitly created. Everyone knows that intand Integer, longand Longcan be converted to each other (autoboxing and unboxing). for example:
public static void main(String[] args) {
    Long sum = 0L;
    for (long i = 0; i < Integer.MAX_VALUE; i++) {
        sum += i;
    }
    System.out.println(sum);
}

There is no problem with this code, but the objects that are not needed to create the pen are hidden in the middle. Since it sumis declared as a Longtype, each loop operation needs to be sumconverted to a Longtype, which increases the creation of objects. In fact, you just need to Long sum = 0Lchange it long sum = 0Lto .

== Therefore, in program development, try to avoid the interaction of basic types and boxed types to prevent the creation of unnecessary objects. ==

Having said so much, it is not to let everyone avoid creating objects in development. In fact, most objects can be created directly, but you need to pay attention to the process of looping, boxing, and object creation is very time-consuming to avoid wasting unnecessary resources.

References

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325950119&siteId=291194637