Java Program Optimization: string manipulation, basic operation methods and other optimization strategies (ii)

Source: Internet
Author: User
Tags bitwise

Data definition, Operational logic optimizationUsing local variables

The parameters passed when the method is called and the temporary variables created in the call are stored in the stack and read and write faster. Other variables, such as static variables, instance variables, and so on, are created in the heap and are slow to read and write. The code shown in Listing 12 shows the comparison of operating times using local variables and static variables.

Listing 12. Local variables VS static variables
public class Variablecompare {public static int b = 0; public static void Main (string[] args) {int a = 0; Long StartTime = System.currenttimemillis ();  for (int i=0;i<1000000;i++) {a++;//defines a local variable} System.out.println (System.currenttimemillis ()-starttime) in the function body; StartTime = System.currenttimemillis (); for (int i=0;i<1000000;i++) {b++;//defines a local variable} System.out.println (System.currenttimemillis ()-starttime) in the function body; }}

The post-run output is shown in Listing 13.

Listing 13. Run results
11T

The two sections of the code run at 0ms and 15ms respectively. This shows that local variables are accessed much faster than the class's member variables.

Bit operation instead of multiplication method

Bitwise operations are the most efficient of all operations. Therefore, you can try to improve the speed of the system by using bit operations instead of some arithmetic operations. The most typical is the multiplication operation optimization for integers. The code shown in Listing 14 is an implementation that uses arithmetic operations.

Listing 14. Arithmetic operations
public class Yunsuan {public static void main (String args[]) {Long start = System.currenttimemillis (), Long a=1000; for (i NT i=0;i<10000000;i++) {a*=2; a/=2;} System.out.println (a); System.out.println (System.currenttimemillis ()-start); Start = System.currenttimemillis (); for (int i=0;i<10000000;i++) {a<<=1; a>>=1;} System.out.println (a); System.out.println (System.currenttimemillis ()-start); }}

Run the output as shown in Listing 15.

Listing 15. Run results
1000546100063

The two pieces of code perform exactly the same function, in each loop, the integer 1000 is multiplied by 2, and then divided by 2. The first cycle takes 546ms, and the second cycle takes 63ms of time.

Replace switch

The keyword switch statement is used for multi-conditional judgments, and the switch statement functions like a if-else statement, which has the same performance. However, the switch statement has a performance-enhancing space. The code shown in Listing 16 illustrates the contrast between Switch and If-else.

Listing 16.Switch Examples
Public class switchcompareif {public static int switchtest (int value) {int  i = value%10+1;switch (i) {case 1:return 10;case 2:return 11;case 3: Return 12;case 4:return 13;case 5:return 14;case 6:return 15;case 7: Return 16;case 8:return 17;case 9:return 18;default:return -1;}} Public static int arraytest (Int[] value,int key) {int i = key%10+1;if (i >9 | |  i<1) {return -1;} Else{return value[i];}}  public static void main (String[] args) { int chk = 0; long  start=system.currenttimemillis ();  for (int i=0;i<10000000;i++) { chk =  Switchtest (i);  } system.out.println (System.currenttimemillis ()-start); chk = 0;  Start=system.currenttimemillis ();  int[] value=new int[]{0,10,11,12, 13,14,15,16,17,18}; for (int i=0;i<10000000;i++) { chk = arraytest (value,i);  }  system.out.println (System.currenttimemillis ()-start);  }}

Run the output as shown in Listing 17.

Listing 17. Run results
17293

Using a sequential array instead of a switch statement, since the random access to the data is very fast, at least better than the branch of switch to judge, from the above example can see the comparison of the efficiency gap nearly 1 time times, the switch method time-consuming 172ms,if-else method time-consuming 93ms.

One-dimensional arrays instead of two-dimensional arrays

JDK Many class libraries are data storage implemented using arrays, such as ArrayList, vectors, etc., the advantage of the array is that random access performance is very good. One-dimensional arrays and two-dimensional arrays have different access speeds, and one-dimensional arrays have better access speeds than two-dimensional arrays. In a performance-sensitive system, two-dimensional arrays are used, and the two-dimensional arrays are converted to one-dimensional arrays and processed to improve the response speed of the system.

Listing 18. Array mode comparison
Public class arraytest { public static void main (String[] args) {  Long start = system.currenttimemillis ();  int[] arraysingle = new int[ 1000000]; int chk = 0; for (int i=0;i<100;i++) { for (int j=0;j< arraysingle.length;j++) { arraysingle[j] = j; } } for (int i=0;i<100;i++) {  for (int j=0;j<arraysingle.length;j++) { chk = arraysingle[j]; } }  System.out.println (System.currenttimemillis ()  - start);  start =  System.currenttimemillis (); int[][] arraydouble = new int[1000][1000]; chk  = 0; for (int i=0;i<100;i++) { for (int j=0;j<arraydouble.length;j++) { for ( int k=0;k<arraydouble[0].length;k++) { arraydouble[i][j]=j; } } } for (int  i=0;i<100;i++) { for (int j=0;j<arraydouble.length;j++) { for (int k=0;k<arraydouble[0].length;k++) { chk =  arraydouble[i][j]; } } } system.out.println (System.currenttimemillis ()  -  Start);   start = system.currenttimemillis ();  arraysingle = new int[ 1000000]; int arraysinglesize = arraysingle.length; chk = 0; for (int  i=0;i<100;i++) { for (int j=0;j<arraysinglesize;j++) { arraysingle[j] = j;  } } for (int i=0;i<100;i++) { for (int j=0;j<arraysinglesize;j++) { chk  = arraysingle[j]; } } system.out.println (System.currenttimemillis ()  -  Start);   start = system.currenttimemillis ();  arraydouble = new int[ 1000][1000]; int arraydoublesize = arraydouble.length; int firstsize =  arraydouble[0].length;&nbSp;chk = 0; for (int i=0;i<100;i++) { for (int j=0;j<arraydoublesize;j++) {  for (int k=0;k<firstsize;k++) { arraydouble[i][j]=j; } } } for (int i =0;i<100;i++) { for (int j=0;j<arraydoublesize;j++) { for (int k=0;k<firstsize;k++) {  chk = arraydouble[i][j]; } } } system.out.println (System.currentTimeMillis ()  - start);  }}

Run the output as shown in Listing 19.

Listing 19. Run results
343624287390

The first code operation is the assignment of a one-dimensional array, the value of the procedure, the second code operation is a two-dimensional array assignment, the value process. One-dimensional arrays can be seen in a way that is nearly half the time of a two-dimensional array. In the array, if you can reduce the assignment operation, it can reduce the operation time and speed up the running of the program.

Extracting an expression

In most cases, the repetitive work of code is not a threat to performance because of the high-speed operation of the computer, but there are many places that can be optimized if you want to achieve the best of the system.

Listing 20. Extracting an expression
Public class duplicatedcode { public static void beforetuning () { long  start = system.currenttimemillis ();  double a1 = math.random ();  double  a2 = math.random ();  double a3 = math.random ();  double a4 =  math.random ();  double b1,b2; for (int i=0;i<10000000;i++) { b1 = a1* A2*a4/3*4*a3*a4; b2 = a1*a2*a3/3*4*a3*a4; } system.out.println ( System.currenttimemillis ()  - start);  }  public static void aftertuning () { long start = system.currenttimemillis ();  double a1 = math.random () ;  double a2 = math.random ();  double a3 = math.random ();  double  a4 = math.random ();  double combine,b1,b2; for (int i=0;i<10000000;i++) {  combine = a1*a2/3*4*a3*a4; b1 = combine*a4; b2 = combine*a3; } system.out.println ( System.currenttimemillis ()  - start);  }  public static void main (String [] args] { duplicatedcode.beforetuning ();  duplicatedcode.aftertuning ();  }}

Run the output as shown in Listing 21.

Listing 21. Run results
202110

The difference between the two pieces of code is that the repeating formula is extracted, so that the formula is only executed once per loop calculation. Time consuming 202ms and 110ms respectively, it can be seen that extracting complex repetitive operations is quite meaningful. This example tells us that in the loop body, if you can extract the calculation formula outside the loop body, it is best to extract, as far as possible to make the program less repetitive calculations.

Optimize loops

When performance problems become the main contradiction of the system, you can try to optimize the cycle, such as reducing the number of cycles, which may speed up the program.

Listing 22. Reduce cycle times
public class Reduceloop {public static void beforetuning () {Long start = System.currenttimemillis (); int[] array = new int [9999999]; for (int i=0;i<9999999;i++) {Array[i] = i;} System.out.println (System.currenttimemillis ()-start);} public static void Aftertuning () {Long start = System.currenttimemillis (), int[] array = new int[9999999]; for (int i=0;i&l t;9999999;i+=3) {Array[i] = i; array[i+1] = i+1; array[i+2] = i+2;} System.out.println (System.currenttimemillis ()-start);} public static void Main (string[] args) {reduceloop.beforetuning (); reduceloop.aftertuning ();}}

Run the output as shown in Listing 23.

Listing 23. Run results
26531

This example shows that by reducing the number of cycles, the time taken is reduced to the original 1/8.

Boolean operations instead of bitwise operations

Although bit operations are much faster than arithmetic operations, using bitwise operations instead of Boolean operations is indeed a very bad choice when it comes to conditional judgment. When the condition is judged, Java makes a fairly good optimization of the boolean operation. Suppose there are expressions A, B, c Boolean operation "A&&b&&c", according to the logic and characteristics, as long as there is an item in the whole Boolean expression returns false, the entire expression will return false, so when the expression A is false, The expression returns false immediately, and no more expressions B and C are evaluated. At this point, expressions A, B, C need to consume a lot of system resources, this processing can save these computing resources. Similarly, when calculating the expression "a| | b| | C "When any of a, B, or c,3 expressions evaluates to true, the whole expression returns true immediately without evaluating the remaining expression. Simply put, in the calculation of a Boolean expression, as long as the value of the expression can be determined, it is returned immediately, and the calculation of the remaining subexpression is skipped. If the bitwise operation (bitwise AND, bitwise, OR) is used instead of logic and logic or, although the bit operation itself has no performance problem, the bitwise operation always calculates all the sub-expressions and then gives the final result. Therefore, from this point of view, using bitwise operations instead of Boolean operations can make the system perform many invalid computations.

Listing 24. Comparison of Operation modes
Public class operationcompare { public static void booleanoperate () {  Long start = system.currenttimemillis ();  boolean a = false; boolean  b = true; int c = 0; //The following loop begins the bitwise operation, and all the calculation factors in the expression are used to calculate the  for (int  i=0;i<1000000;i++) { if (a&b& "test_123". Contains ("123")) { c = 1; }  } system.out.println (System.currenttimemillis ()  - start); }  public  Static void bitoperate () { long start = system.currenttimemillis ();  boolean  a = false; boolean b = true; int c = 0; // The following loop begins the Boolean operation, and the expression is evaluated only  a  the condition  for (int i=0;i<1000000;i++) { if (a&&b&& "Test_123". Contains ("123")) { c = 1; } } system.out.println ( System.currenttimemillis ()  - start); &nbsP;}   public static void main (String[] args) { operationcompare.booleanoperate () ;  operationcompare.bitoperate ();  }}

Run the output as shown in Listing 25.

Listing 25. Run results
630

The example shows that the Boolean calculation is much better than the bitwise operation, but this result does not indicate that the bitwise operation is slower than the logical operation, because in all the logic and operation, the expression "" test_123 "is omitted. The computation of contains (" 123 "), and all bitwise operations fail to omit this part of the system overhead.

Using ArrayCopy ()

Data replication is a highly used feature, and the JDK provides an efficient API to implement it. The System.arraycopy () function is a native function, usually the performance of the native function is better than the normal function, so, only in the performance considerations, in software development, the native function should be called whenever possible. ArrayList and vectors use a lot of system.arraycopy to manipulate data, especially the movement of elements within the same array and the copying of elements between different arrays. The essence of arraycopy is to allow the processor to use an instruction to process multiple records in an array, a bit like a string operation instruction in assembly language (LODSB, LODSW, LODSB, STOSB, STOSW, STOSB), just specify the head pointer and start the loop. That is, once the instruction is executed, the pointer moves back one position, and the number of times the data is manipulated. If you need to replicate the array in your application, you should use this function instead of implementing it yourself. The specific application is shown in Listing 26.

Listing 26. Example of copying data
Public class arraycopytest {public static void arraycopy () {int size =  10000000; int[] array = new int[size]; int[] arraydestination =  new int[size]; for (int i=0;i<array.length;i++) { array[i] = i; }  long start = system.currenttimemillis ();  for (int j=0;j>1000;j++) {  System.arraycopy (array, 0, arraydestination, 0, size);//Use  System  level local   arraycopy  Way  } system.out.println (System.currenttimemillis ()  - start);} Public static void arraycopyself () {Int size = 10000000; int[] array  = new int[size]; int[] arraydestination = new int[size]; for (int  i=0;i<array.length;i++) { array[i] = i; } long start =  System.currenttimemillis ();  for (int i=0;i<1000;i++) { for (int j=0;j<size;j++) { arraydestination[j] = array[j];// Own implementation of the way, using the array of Data interchange method  } } system.out.println (System.currenttimemillis ()  - start);}  public static void main (String[] args) { arraycopytest.arraycopy ();  Arraycopytest.arraycopyself ();  }}

The output is shown in Listing 27.

Listing 27. Run results
023166

The example above shows that copying using the Arraycopy method is very fast. The reason is that arraycopy belongs to the local method, and the source code is shown in listing 28.

Listing 28.arraycopy Methods
public static native void Arraycopy (object src, int srcpos, object dest, int destpos, int length);

SRC-source array; srcpos-the starting position in the source array; dest-target array; destpos-the starting position in the target data; length-the number of array elements to copy. The method shown in listing 28 uses the native keyword, called the underlying function written in C + +, which can be seen as the underlying function in the JDK.

Conclusion

Java Program Design Optimization has many aspects to start with, the author will be in a series of ways to gradually cover all areas. This article is the first article of this series, mainly introduced the string object operation correlation, the data definition aspect optimization scheme, the Computation logic optimization and the suggestion, starts from the actual code demonstration, has carried on the validation to the optimization suggestion and the scheme. The author always believes that there is no optimization scheme is hundred effective, need readers according to the actual situation to choose, practice.

Java Program Optimization: string manipulation, basic operation methods and other optimization strategies (ii)

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.