Java code optimization series (1): the beginning of the article

Source: Internet
Author: User

Java code optimization series (1): the beginning of the article

Reprinted please indicate the source: http://blog.csdn.net/lhy_ycu/article/details/45506549


Before starting the article, I would like to add the use of the instanceof keyword in the Java Learning Series and its traps. Brief description: instanceof is a simple binary operator used to determine whether an object is an instance of a class. As long as the operations on the left and right of instanceof have an inheritance or implementation relationship, the program can be compiled. The following uses a simple example to describe how to use the instanceof keyword and its traps:

Class A <T> {public boolean isDateInstance (T t) {return t instanceof Date;} public class InstanceofTest {public static void main (String [] args) {// true. A String Object is an Object instance (in java, the Object is the parent class of all classes) System. out. println ("zhangsan" instanceof Object); // false. An Object is a parent class, and its Object is obviously not an instance of the String class System. out. println (new Object () instanceof String); // true. A String object is a String instance System. out. println (new String () instanceof String); // compilation fails. 'A is a char type, that is, the basic type // System. out. println ('A' instanceof Character); // false. As long as the left operand is null (essentially non-typed), The result returns falseSystem. out. println (null instanceof String); // false. NullSystem. out. println (String) null instanceof String) even if the null value is strongly converted; // compilation fails. Because Date and String do not inherit or implement the relationship // System. out. println (new Date () instanceof String); // false. T is already of the Object type when compiled into bytecode. Because a "lisi" real parameter String is passed, T is actually of the String type. System. out. println (new A (). isDateInstance ("lisi "));}}
[Note] instanceof can only be used for object judgment and cannot be used for basic type judgment.

The topic is officially entered below. Let's start with an auto-increment trap.

1) Self-increment traps

int num = 0;for (int i = 0; i < 100; i++) {num = num++;}System.out.println("num = " + num);
What is the printed result? The answer is 0. Why? Let's take a look at the execution steps. The detailed steps for the first loop of the program are as follows: JVM copies the num value (0) to the Temporary Variable Area, and then adds the num value to 1, this is the value of num is 1, and then the value of the Temporary Variable Area is returned. Note that this value is 1 and has not been modified. Finally, the return value is assigned to num. At this time, the value of num is reset to 0. Simply put, the three steps are int temp = num; num + = 1; return temp. Therefore, the print result is still 0, and num is always in the original state.

Optimization: Modify num = num ++; To num ++.


2) is a constant actually a variable?

Can constants become variables? The answer is yes, but this approach is not recognized.

Public static final int RAND_CONST = new Random (). nextInt (); public static void main (String [] args) {// you can see that the result has changed by printing it several times, that is to say, when defining a constant, its value does not remain unchanged at runtime. out. println ("has the constant changed? "+ RAND_CONST );}
Optimization suggestion: Make sure that the constant value remains unchanged during runtime.Therefore, RAND_CONST can be directly assigned a value and written to death during definition.


3) Can you see if the letter "l" is in the upper case of I, Number 1, or letter l?

public static  long l = 11;

Optimization: uppercase letters and suffixes l


4) are the types of the Three-object operators inconsistent?

int i = 70;System.out.println(i < 100 ? 80 : 90.0);
The print result is unexpectedly 80.0. Why? I <100 is true, but since the last operand is 90.0, It is a floating point number, then the compiler will convert the second operand 80 to 80.0 floating point number, unified result type, therefore, the output is 80.0.
Optimization: Change 90.0 to 90

5) do not reload the method containing variable length parameters.

Brief description: The variable length parameter must be the last parameter of the method, and a method cannot define multiple variable length parameters.

Public class Test01 {public static void fruitPrice (int price, int discount) {float realPrice = price * discount/100366f; System. out. println ("result of Non-variable length parameter: realPrice =" + realPrice);} public static void fruitPrice (int price, int... discounts) {float realPrice = price; for (int discount: discounts) {realPrice = price * discount/100366f;} System. out. println ("result of the variable length parameter: realPrice =" + realPrice);} public static void main (String [] args) {fruitPrice (48888, 85 );}}

What is the printed result? The answer is: the result of a non-variable-length parameter: realPrice = 41554.8, that is, the program executes the first method without executing the variable-length parameter method. Why? During Java compilation, it will first be processed based on the number and type of real parameters (here two are all real parameters of the int type, note that they are not converted to an int array, that is to say, find the fruitPrice (int price, int discount) method and confirm that it meets the method signature conditions. Because the compiler also loves "Laziness", the program will execute the first method. Let's look at another one:

Public class Test02 {public void method1 (String str, Integer... integers) {System. out. println ("the method of variable length parameter type Integer is called... ");} public void method1 (String str, String... strs) {System. out. println ("the method with the variable length parameter type of String is called... ");} public static void main (String [] args) {Test02 t = new Test02 (); // compilation fails. Although both methods meet the requirements, the compiler does not know which one to call, so an error is reported. T. method1 ("test02"); // compilation fails. Because [directly adding null is of no type], the reason is the same as above. T. method1 ("test02", null );}}

For t. method ("test02", null); if we declare String [] strs = null or Integer [] ints = null in advance; that is to say, let the compiler know that the null is of the String or Integer type, then it can be compiled.

6) use static import with caution

This is easy to understand, because the function of static import is to introduce the class members (static variables and static methods) of a class to this class, if this class also has members of the same name at this time, confusion may occur and subsequent maintenance will be troublesome.

Optimized: type. class member

7) do not change the type silently

Public class Test03 {// The speed of light is 0.3 million kilometers public static final int LIGHT_SPEED = 30*10000*1000; public static void main (String [] args) {long distance = 8*60 * LIGHT_SPEED; // print the result (negative): the distance between the earth and the sun is-2028888064System. out. println ("the distance between the earth and the sun is:" + distance );}}
Why is it a negative number? This is because Java performs operations before type conversion.. The three operation parameters of distance are of the int type. Although the three results are equal, they are also of the int type, but they have exceeded the maximum range of the int value. Therefore, they are negative, and then converted to the long type, the result is still negative. Solution: long distance = 1L * 8*60 * LIGHT_SPEED; 1L is a long integer, and the equation type on the right is automatically upgraded. The calculated result is also a long integer.

Optimization: when converting basic types, it is best to use the method of active Declaration for calculation.

8) is the packaging class null?

Public static void main (String [] args) {List <Integer> list = new ArrayList <Integer> (); // automatically boxed (the basic type is converted to the packaging type ). The packing process is implemented by calling the valueOf method. List. add (1); list. add (2); list. add (null); // automatically unpack (the packaging type is converted to the basic type ). The unpacking process is implemented by default by calling the intValue method of the packaging object. Int count = 0; for (int item: list) {count + = item;} System. out. println ("count =" + count );}
Java. lang. NullPointerException is reported in the running result. The reason is simple: in the case of unpacking, The intValue method of the packaging object is called by default. Because the packaging class is null, a null pointer exception is reported. Solution:

for (Integer item : list) {count += (item == null) ? 0 : item;}

Optimization: the null check is required when the packaging type is involved in the operation.

9) Make the tool class uninstantiated

The methods and attributes of the tool class are static and can be accessed without generating an instance. Besides, the class members only have one copy in the memory, and jdk also works well. Because you do not want to be initialized, you can set the constructor to private.

Public class UtilClass {// constructor privatize private UtilClass (){}}
However, the problem is that there may be many methods in the tool class, and a new object is accidentally created, which is not found at a time. In this way, no instance is actually needed.

Optimization: when using tool classes, make sure that all accesses are performed by class names.

Public class UtilClass {// constructor private UtilClass () {throw new Error ("please don't instantial this util class ...");}}

10) do not take the initiative to recycle garbage

Do not call System. gc (); to actively recycle the garbage.Because System. gc stops all responses, you can check whether there are recyclable objects in the memory. Check all objects and process the junk objects.. This is highly risky for an application System. If it is a web project, call System. gc will suspend all requests and wait until the execution of the garbage collector is completed (which may seriously affect normal business operations). If there are many objects in the web project, then System. gc execution time is very time-consuming, so it is best not to take the initiative to recycle garbage.

11) static variables must be declared first and then assigned (or used)

public class Test01 {static {num = 20;}public static int num = 2;public static void main(String[] args) {System.out.println(num);}}
What is the result? The printed result is: 2. Why? This is because static variables (class variables) are allocated to the data zone during class loading, It has only one copy in the memory,Specifically, static variables are first loaded during class initialization, while JVM searches for all static declarations in the class and allocates the address space (no value assigned at this time ), then the JVM will perform the Assignment Based on the sequence of static values in the class (including static class assignment and static code block assignment.

Optimized: the static variables are first declared and then used.

References: Writing high-quality code



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.