By using some auxiliary tools to find bottlenecks in your program, you can optimize the code for the Bottleneck section. There are generally two scenarios: optimizing the code or changing the design method. We typically choose the latter because not calling the following code can improve program performance better than calling some optimized code. A well-designed program can streamline code to improve performance.
Some of the methods and techniques used in Java program design and coding to improve the performance of Java programs are presented below.
1. The generation and sizing of objects.
A common problem with Java programming is that it does not take advantage of the functions provided by the Java language itself, which often generates a large number of objects (or instances). Since the system not only takes time to generate objects, it may also take time to garbage collect and process these objects later. Therefore, generating too many objects will have a significant effect on the performance of the program.
Example 1: About String, stringbuffer,+ and append
The Java language provides an operation for a string type variable. However, if used improperly, it will affect the performance of the program. As in the following statement:
String Name=new string ("Huangweifeng");
System.out.println (name+ "is my Name");
Seems to have been very streamlined, but it is not so. To generate binary code, the following steps and actions are performed:
(1) Generate a new string (str_1);
(2) copying the string;
(3) Load string constant "Huangweifeng" (str_2);
(4) The frame (constructor) that invokes the string;
(5) Save the string into the array (starting from position 0);
(6) Obtaining the static out variable from the Java.io.PrintStream class;
(7) Generate a new string buffer variable StringBuffer (str_buf_1);
(8) Copy the string buffer variable;
(9) The frame (constructor) that invokes the string buffer;
(10) Save the string buffer into the array (starting from position 1);
(11) The Append method in the string buffer (StringBuffer) class is invoked with str_1 as the parameter;
(12) Load string constant "is my Name" (str_3);
(13) The Append method in the string buffer (StringBuffer) class is invoked with Str_3 as the parameter;
(14) Execute ToString order for str_buf_1;
(15) Call the Println method in the out variable to output the result.