How to mine performance from Java

Source: Internet
Author: User

Java, as a high-level language, has its own advantages and disadvantages. Currently, the advantages and disadvantages of Java are not easy to draw conclusions, but we can use the operating system to consider the advantages and disadvantages of advanced languages: first, as a component in the operating system, interfaces and services are provided upwards, and hardware operations and management are provided downward, operating Systems with this characteristic can be popularized quickly at the technical level and more people should deal with development. Remember to say something in the book of the shadows. I will change it to such a version after I agree with it, the underlying programmer is the real challenge, because the underlying language has a longer change cycle than the high-level language, which has a greater impact and difficulty. Therefore, we usually use the advanced language for development, for example, we can perform high-level development on encapsulated virtual machines and APIs in Java. The real underlying layer is specific to the Operations. Generally, programmers do not understand this, I remember that when I was a sophomore, I developed a large number of DLL components, which increased the performance by 20 times. This example shows that the performance optimization in the underlying language is more powerful, however, as a senior language programmer, we also need to consider ways to save system overhead and operational efficiency.
First of all, I think the method for saving system overhead and running efficiency can be expressed using this formula: P = V * T or (V + T) P indicates the total efficiency. V indicates the space T as the time.
All those who have learned about databases should know that we always seek a better balance between time and space. Fish and bear's paw cannot have both sides. This is especially important. I will demonstrate several small codes below, how can we find a balance between code readability and code running efficiency in Java? Of course, the balance between running efficiency will also be demonstrated, so that your Java code will not be dragged.
1. flexible use of >>and <<
In Java, the operation of moving left and right is supported. We didn't have an anti-code or Code complement mechanism during compilation. Why, in fact, there are few computing mechanisms and instruction sets in our CPU. The main task of the CPU is to execute many addition operations. using binary, we can clearly talk about the hardware switch and binary union, the reverse code and the complement mechanism Change subtraction to addition to transform multiplication to addition, division to multiplication and then to addition, so that the CPU is mainly responsible for addition operations, it can be said to be a calculator. Let's look at this Code:
Public class test1 {
Public static void main (string [] ARGs ){
Int num = 8;
Int ans_1 = 0;
Int ans_2 = 0;

Long start = system. currenttimemillis ();
For (INT I = 0; I <10000000; I ++ ){
Ans_1 = num/2;
}
System. Out. println ("regular 1000000 Division calculation consumption:" + (system. currenttimemillis ()-Start) + "Ms ");
System. Out. println ("general calculation result" + ans_1 );

Start = system. currenttimemillis ();
For (INT I = 0; I <10000000; I ++ ){
Ans_2 = num> 1;
}
System. Out. println ("optimized 1000000 Division calculation consumption:" + (system. currenttimemillis ()-Start) + "Ms ");
System. Out. println ("optimization calculation result" + ans_2 );

}
}


We can clearly see the time savings and comparison in 1000000 identical computations, this time saving is a major performance bottleneck for high concurrency processing of handheld devices and servers.
2. Local and global variables
When learning the basics of Java, we clarified the different advantages of local variables and global variables. global variables are very large in maintaining the overhead of reference pointing, especially when the maintenance data volume is large, it is easy to cause high energy consumption, when using a high-level language such as Hibernate, we will find that in many cases we need to optimize the code relatively, however, local variables have relatively low overhead and limited lifecycles when maintaining references, which leads to higher performance. The disadvantage is that the Code is not readable, this is the least noticeable in our daily programming. Let's take a look at this Code:
Package com. cs. test;
Public class Test2 {
Static int num = 8;
Public static void main (string [] ARGs ){
Long start = system. currenttimemillis ();
Add1 ();
System. Out. println ("directly manipulate global variable consumption:" + (system. currenttimemillis ()-Start) + "Ms ");

Start = system. currenttimemillis ();
Add2 ();
System. Out. println ("local variable to operate global variable consumption:" + (system. currenttimemillis ()-Start) + "Ms ");

}

Private Static void Add1 (){
// Directly operate on global variables
For (INT I = 0; I <10000000; I ++ ){
Num + = I;
}
}
Private Static void Add2 (){
// Use local variables to operate global variables
Int temp = num;
For (INT I = 0; I <10000000; I ++ ){
Temp + = I;
}
Num = temp;
}
}

The results are very detailed and I will not talk nonsense. when the temp variable in Add2 is used, if the Business Code is longer or more complex, it is easy to cause reading inconvenience. This is a typical practice of changing the space for time, if you are interested, use the javac command to monitor the memory.
3. The switch... case... statement is more suitable than if... else if... nesting or superposition.
When dealing with many choices, we usually think of if... else instead of switch... case, even switch... in case, it is easy to miss the default so that the program has some tricky vulnerabilities. in addition, in the new features of jdk1.5, you can use Enum to enhance the selection function, so that it is not limited to int and Char....
Package com. cs. test;
Public class test3 {
Private Static Enum choose {
First, second
}
Public static void main (string [] ARGs ){
Choose choose = choose. first;
Switch (choose ){
Case first:
System. Out. println ("first ");
Break;
Case second:
System. Out. println ("second ");
Break;
Default:
System. Out. println ("default ");
}
}
}
4. Pay attention to the performance loss that may easily occur in loop control.
Generally, when we iterate a collection, it is easy to adopt the following programming method. I will compile and test the code to see which one is more efficient:
Import java. util. arraylist;
Public class test4 {
Public static void main (string [] ARGs ){
Arraylist <string> V = new arraylist <string> ();
For (INT I = 0; I <1000000; I ++ ){
V. Add ("1234" + I );
}

// Regular code writing
Long start = system. currenttimemillis ();
For (INT I = 0; I <v. Size (); I ++ ){
V. Get (I );
}
System. Out. println ("regular 1000000 read computing consumption:" + (system. currenttimemillis ()-Start) + "Ms ");
// Optimize code writing
Start = system. currenttimemillis ();
Int size = V. Size ();
For (INT I = 0; I <size; I ++ ){
V. Get (I );
}
System. Out. println ("optimized code writing: optimized 1000000 read computing consumption:" + (system. currenttimemillis ()-Start) + "Ms ");

// ANOTHER METHOD
Start = system. currenttimemillis ();
For (INT I = V. Size ()-1; I> = 0; -- I ){
V. Get (I );
}
System. Out. println ("another method: optimize 1000000 read computing consumption:" + (system. currenttimemillis ()-Start) + "Ms ");

}
}

5. Usage of stringbuffer and string
Public class test5 {
Public static void main (string [] ARGs ){
String str1 = "Temp ";
Stringbuffer str2 = new stringbuffer ("Temp ");

// Regular code writing
Long start = system. currenttimemillis ();
For (INT I = 0; I <10000; I ++ ){
Str1 + = (I );
}
System. Out. println ("string regular 1000000 increase computing consumption:" + (system. currenttimemillis ()-Start) + "Ms ");
// Optimize code writing
Start = system. currenttimemillis ();
For (INT I = 0; I <10000; I ++ ){
Str2.append (I );
}
System. Out. println ("stringbuffer optimized 1000000 times to increase computing consumption:" + (system. currenttimemillis ()-Start) + "Ms ");

}
}

6. Try {} catch {} blocks may have room for optimization in some cases
Sometimes we can force some possible statements to be called in try {} catch {}. When an exception occurs, it is forcibly thrown to the code at the upper level, in this case, we can combine if... else... to avoid additional overhead when the system captures exceptions and make the program's normal fault tolerance more powerful, we can look at a method that can be improved:
Public class test6 {
Public static void main (string [] ARGs ){
Mytest x = NULL;

// Rape throw
Try {
X. Show ();
} Catch (nullpointerexception e ){
E. printstacktrace ();
}

// Politely throw
If (x = NULL ){
System. Out. println ("problem occurred ");
} Else {
X. Show ();
}

}

Private Static class mytest {
Public void show (){
System. Out. println ("display information ");
}
}

}

Today, due to the time relationship, I will write it here. Next time, I will analyze some performance optimization and Cache Usage issues in Io operations and present the code, we will discuss how to encapsulate the buffer view mechanism, random file multi-thread access and download, memory mapping mechanism, and Io. I hope you can give me some suggestions and help me improve it together.
This article is original and reprinted with the source to be declared

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.