Creating and destroying objects - to avoid creating unnecessary objects

Reference: "Effective Java", "Java core technology Volume 1"

Based on the review

1. autoboxing

The most common basic types, such as int, long, float, etc., there is a corresponding wrapper class. The wrapper class names and also their correspondence, such as: Integer, Long, Float like.

As we like to define a list of integers, but inside angle brackets is not allowed to write int, this time you need to use Integer, as follows:

ArrayList<Integer> arrayList=new ArrayList<Integer>();

When we add to this set of numbers, in fact, we went through the process of automatic packing

arrayList.add(3);

Code above into practically automatically:

arrayList.add(Integer.valueOf(3));

This transformation is called automatic packing.

Conversely, when we object is assigned to an Integer type int, will automatically unpack.

Some need to be aware of:

1.Integer type of comparison to use equals.

2. Packing and unpacking recognized by the compiler, rather than a virtual machine. Like the above conversion is to generate a corresponding byte code by a compiler, the virtual machine to execute only these bytecodes.

 

Avoid creating unnecessary objects

1. desirable to reuse individual objects

In general, it is best to reuse a single object instead of each time you need the same functionality to create a new object. Reuse is fast and popular way.

If the object is immutable, it can always be reused.

 counterargument:

STR = String new new String ( "reusable object");

When the above statement is executed each time creates a new String instance. After the improvements are as follows:

String str = "reusable object";

The above code, all code running in the same virtual machine, as long as they contain the same character string, the object will be reused.

 

2. Priority static factory method instead of a constructor

The constructor creates a new object each time it is invoked, and the static factory method will not do.

Static factory method: https://www.cnblogs.com/lbhym/p/11787505.html

 

3. Automatic packing may create unwanted objects

To use Basic type instead of the wrapper class.

Examples are given in the book:

private static long sum(){
  Long sum=0L;
  for(long i=0;i<=Integer.MAX_VALUE;i++){
    sum+=i;
}  
  return sum;
}

The above program must use a type long int can not be received because the sum of the positive integer int.

The sum statement became Long, actual operating results are correct, but time has a lot of long, each machine may not be the same.

 

Guess you like

Origin www.cnblogs.com/lbhym/p/11813834.html