Java rule analysis

xiaoxiao2021-03-06  59

1. Avoid using the New keyword to create a String object. PRIVATE? STRING? STR? =? new? string? ("Hello"); // This newly built object is redundant.

Because of the invariance of String objects, every assignment of the String object produces a new object.

Related to this, Java should avoid using a string connection. Based on the same reason, a large number of temporary objects are generated when using the ' ' operator, which will affect performance. StringBuffer should be used instead of ' ' operation.

2. Regular SUPER.FINALIZE? () Finalize is often a method in the Object class, but the Finalize function does not automatically implement chain calls. In this way, we can implement the Finalize call from the bottom to top, that is, release your own resources, then release the resources of the parent class.

About Finalize, need to be used with caution.

According to the Java language specification, JVM guarantees that this object is unreachable before calling the Finalize function, but JVM does not guarantee that this function will be called. In addition, the specification also guarantees that the finalize function runs up to once.

Try to use the Finalize function. The Finalize function is the opportunity to provide the programmakers to the programmaked object or resource. However, it will increase the workload of the GC, so try to recycle resources in Finalize mode.

The reasons are three, which, GC to support the Finalize function, make a lot of additional work to override the object. Second, after the Finalize is completed, the object may become upacted, and the GC also checks if the object is up. Therefore, using Finalize will reduce the operating performance of GC. Third, since the GC call finalize is uncertain, it is not sure to release resources in this way.

Typically, Finalize is used for some disclosures that are not easy to control, and very important resources, such as some I / O operations, and data connection. The release of these resources is critical to the entire application. In this case, the programmer should be mainly based on the program itself management (including release) resources, supplemented with the Finalize function to form a double insurance management mechanism, and should not rely on Finalize to release resources. .

转载请注明原文地址:https://www.9cbs.com/read-119588.html

New Post(0)