In Java programming, java programming tries its best to achieve performance.

Source: Internet
Author: User
Tags finally block

In Java programming, java programming tries its best to achieve performance.

1. Use the singleton whenever possible

The use of Singleton can reduce the load burden, shorten the loading time, and improve the loading efficiency, but not all of them are applicable to singleton. Simply put,The Singleton is applicable to the following three scenarios:

First, control resource usage and control concurrent resource access through thread synchronization;

Second, control the generation of instances to save resources;

Third, control data sharing and allow communication between multiple irrelevant processes or threads without establishing a direct association.

2.Avoid using static variables whenever possible

You know, when an object is defined as referenced by the stataic variable, gc usually does not recycle the memory occupied by this object, such

 

Java code

At this time, the lifecycle of static variable B is synchronized with class A. If Class A is not uninstalled, the object B is resident in the memory until the program ends.

3. Avoid creating too many Java objects.

Try to avoid new objects in the frequently called methods and loops. Because the system not only takes time to create objects, but also takes time to recycle and process these objects, within the scope that we can control, we recommend that you replace objects with basic data types or arrays to maximize the reuse of objects.

 

4. Try to use the final Modifier

Classes with final modifiers cannot be derived. There are many examples of final applications in the Java core API, such as java. lang. String. Specifying final for the String class prevents the user from overwriting the length () method. In addition, if a class is final, all methods of the class are final. The Java compiler will look for opportunities to inline (inline) All final methods (this is related to the specific compiler implementation ). This can increase the performance by an average of 50%.

 

5. Use local variables whenever possible

The parameters passed during method calling and the temporary variables created in the call are saved in the Stack, which is faster. Other variables, such as static variables and instance variables, are created in Heap, which is slow.

6. Try to handle the places of use of the packaging type and basic type

Although the packaging types and basic types can be converted to each other during use, the memory areas generated by the two are completely different. The basic types of data are generated and processed in the stack, the packaging type is an object that generates instances in the heap.

The packaging type is applicable to the processing of collection objects and objects. Other Processing Methods advocate the use of basic types.

(1). Use Boolean. valueOf (boolean B) instead of new Boolean () 

The memory usage of the packaging class is terrible. It is N times the memory usage of the basic type (N> 2), and a new object is also the performance consumption.
Let's take a look at JDK's implementation of Boolean. valueOf (boolean B:
The Boolean class provides two constants:

Java code


The internal implementation of valueOf (boolean B) is:

Java code


Therefore, replacing new Boolean () with boolean. valueOf (Boolean B) can save space and improve performance.

(2) Replace new Integer () with Integer. valueOf (int I () 
Similar to Boolean, there are also many cases where Integer is used to encapsulate int in java Development, and the values represented by int are usually very small. The instantiation of Integer is optimized in sun sdk. The Integer class caches integers in the 128 to 127 States. If Integer is used. valueOf (int I), the input int range is exactly within this, and the static instance is returned. In this way, if we use Integer. valueOf instead of new Integer, the memory usage will be greatly reduced.

7. Use synchronized with caution to minimize synchronize.

We all know that implementing synchronization requires a lot of system overhead as a cost, and may even cause deadlocks, so we should avoid unnecessary synchronization control as much as possible. When the synchronize method is called, the current object is directly locked. Other threads cannot call other methods of the current object until the method is executed. Therefore, the synchronize method should be as small as possible, and the method synchronization should be used instead of the code block synchronization.

8. Use StringBuilder and StringBuffer for string connection whenever possible

Replace "+" with the append method of StringBuffer to add strings. 
N people have already said this N times, so that's not much to say.

I will not talk about this much.

9. Try not to use the finalize method

In fact, it is very difficult to put the resource cleanup in the finalize method. Due to the heavy GC workload, especially when the Young generation memory is reclaimed, the application will be suspended, therefore, the finalize method can be used to clean up resources, resulting in a greater GC burden and worse program running efficiency.

 

10. Try to replace the object with the basic data type

String str = "hello ";

In this method, a "hello" string is created, and the JVM character cache pool also caches this string;

String str = new String ("hello ");

In this case, in addition to creating strings, the String object referenced by str also contains an array of char [] at the bottom layer. The array of char [] Stores h, e, l, l, o in sequence.

 

11. Use HashMap,ArrayList

HashTable and Vector use synchronization mechanisms to reduce performance.

 

12. Create as appropriate as possibleHashMap

When you want to create a large hashMap, make full use of another constructor.

Public HashMap (int initialCapacity, float loadFactor)

To prevent HashMap from performing hash reconstruction multiple times, resizing is a performance-consuming task. By default, initialCapacity is only 16, while loadFactor is 0.75, which indicates the capacity required, you 'd better accurately estimate the optimal size you need. The same is true for Hashtable and Vectors.

 

13. reduce repeated variable calculation as much as possible

For example

For (int I = 0; I <list. size (); I ++)

Should be changed

For (int I = 0, len = list. size (); I <len; I ++)

In addition, you should avoid using complex expressions in a loop. in a loop, loop conditions are calculated repeatedly. If you do not use a complex expression and keep the value of the loop condition unchanged, the program will run faster.

 

14. Avoid unnecessary creation as much as possible

For example

A a = new ();

If (I = 1) {list. add ();}

Should be changed

If (I = 1 ){

A a = new ();

List. add ();}

(4) Avoid too deep class hierarchies and too deep method calls. 

Because both of them occupy a lot of memory (especially method calls are the largest consumer of stack space ).

(5) variables are defined and instantiated only when they are used. 

This is the easiest mistake for beginners to make. variables can be reasonably used and defined and instantiated only when they are used, effectively avoiding the waste of memory space and execution performance, this improves the code efficiency.

(6) avoid declaring the object in the loop body, even if the object occupies little memory space. 

This situation is often encountered in our actual application, and we can easily make similar errors, such as the following code:

Java code


The above practice will waste a lot of memory space. The correct method is as follows:

Java code


In the second writing method above, only one reference to this object is saved in the memory, unlike the first writing method above, the code will generate a large number of object references in the memory, wasting a lot of memory space and increasing the garbage collection load. Therefore, we recommend that you avoid writing the object in the loop body.

15. release resources in finally blocks as much as possible

The resources used in the program should be released to avoid resource leakage. This should be done in finally blocks. Regardless of the execution result of the program, the finally block is always executed to ensure that the resource is properly closed.

 

16. Use shift as much as possible to replace the operation of 'a/B'

"/" Is a very costly operation. Using shift operations will be faster and more effective.

For example

Int num = a/4;

Int num = a/8;

Should be changed

Int num = a> 2;

Int num = a> 3;

Note that annotations should be added when shift is used, because the shift operation is not intuitive and difficult to understand.

 

17. Try to use shift instead of 'a * B '.

Similarly, for the '*' operation, the shift operation will be faster and more effective.

For example

Int num = a * 4;

Int num = a * 8;

Should be changed

Int num = a <2;

Int num = a <3;

 

18. Determine StringBuffer capacity as much as possible

The StringBuffer constrtor creates a character array of the default size (usually 16. In use, if the size exceeds this value, the memory will be re-allocated, a larger array will be created, the original array will be copied, and then the old array will be discarded. In most cases, you can specify the size when creating the StringBuffer, which avoids automatic growth when the capacity is insufficient to improve performance.

For example, StringBuffer buffer = new StringBuffer (1000 );

 

19. Release reference of useless objects as early as possible

In most cases, objects referenced by partial reference variables of a method become junk as the method ends. Therefore, most of the time, the program does not need to explicitly set the reference variable to null.

For example:

 

Java code

The above is unnecessary. With the execution of the method test (), the scope of the variable referenced by obj in the program ends. But if it is changed to the following:

 

Java code

In this case, it is necessary to assign the obj value to null and release the reference to the Object as soon as possible.

 

20. Avoid using 2D arrays whenever possible

The two-dimensional data occupies much more memory space than the one-dimensional array, which is about 10 times more.

 

21. Try to avoid usingSplit

Unless necessary, you should avoid using split. Because split supports regular expressions, the efficiency is relatively low. If it is frequently used for dozens of times, millions of calls will consume a lot of resources, if you need to call split frequently, you can consider using apache's StringUtils. split (string, char). Results can be cached for frequent split operations.

 

22. ArrayList & role list

One is a linear table and the other is a linked list. In a single sentence, ArrayList should be used for random queries as much as possible. ArrayList is better than the sort list, And the sort list also needs to move the pointer. The sort list is better than the ArrayList operation, however, this is a theoretical analysis. This is not the case. It is important to understand the data structure of the two users and take the right medicine.

 

23. Try to use System. arraycopy () instead of copying arrays cyclically.

System. arraycopy () is much faster than copying arrays through loops.

 

24. cache frequently used objects as much as possible

Cache frequently-used objects as much as possible. You can use arrays or HashMap containers to cache objects. However, this method may cause the system to occupy too much cache and degrade performance, we recommend that you use some third-party open-source tools, such as EhCache and Oscache, to cache data. They basically implement caching algorithms such as FIFO and FLU.

 

25. Avoid very large memory allocation whenever possible

Sometimes the problem is not caused by the current heap status, but by allocation failure. The allocated memory blocks must be continuous. As the heap becomes more and more full, it is increasingly difficult to find larger contiguous blocks.

 

26. Use exceptions with caution

When creating an exception, you need to collect a stack trace that describes where the exception was created. When building these stack traces, you need to create a snapshot for the runtime stack, which is a huge overhead. When an Exception needs to be created, the JVM has to say: don't change. I want to save a snapshot as you are, so temporarily stop the inbound and outbound operations. Stack tracing contains not only one or two elements in the runtime stack, but also each element in the stack.

If you create an Exception, you have to pay the price. Fortunately, exception capturing does not overhead much, so try-catch can be used to wrap the core content. Technically, you can even throw an exception at will without a high cost. Performance loss is not caused by throw operations-although it is a bit unusual to throw an exception without a pre-created exception. The real cost is creation exceptions. Fortunately, good programming habits have taught us not to throw exceptions regardless of November. Exceptions are designed for exceptions and should be kept in mind when used.

 

27 if multiple conditions are connected using '|' or '&', place the condition with the highest frequency before the expression.

This tips can often effectively improve the program performance, especially when the if judgment is placed in the loop body, the effect is more obvious.


Some Questions about Java elementary Programming

If you have not copied the wrong question, it will be okay.
1 B
2 B
3 C // It must be C. The first println is commented out.
4 F
5
6 C
7 C
8 B
9 B
10 B
11 D
12 B
13 C
14 D
15 C

//////////////////////////////////////// ////
// 1
Public class BaiduTest {
Public static void main (String [] args ){
System. out. println (add (6, 2 ));
System. out. println (sub (6, 2 ));
System. out. println (mul (6, 2 ));
System. out. println (div (6, 2 ));
}
Public static int add (int x, int y ){
Return x + y;
}
Public static int sub (int x, int y ){
Return x-y;
}
Public static int mul (int x, int y ){
Return x * y;
}
Public static int div (int x, int y ){
Return x/y;
}
}

//////////////////////////////////////// /////
// 2
Import java. math. BigDecimal;

Public class BaiduTest {
Public static void main (String [] args ){
System. out. println (isRightTriangle (3.0, 4.0, 5.0 ));
}
Public static boolean isRightTriangle (double x, double y, double z ){
BigDecimal bx = new BigDecimal (x );
BigDecimal by = new BigDecimal (y );
BigDecimal bz = new BigDecimal (z );
Bx = bx. pow (2 );
By = by. pow (2 );
Bz = bz. pow (2 );
If (bx. add (by). equals (bz )){
Return true;
}
Return false;
}
}... Remaining full text>

Some Questions about Java elementary Programming

If you have not copied the wrong question, it will be okay.
1 B
2 B
3 C // It must be C. The first println is commented out.
4 F
5
6 C
7 C
8 B
9 B
10 B
11 D
12 B
13 C
14 D
15 C

//////////////////////////////////////// ////
// 1
Public class BaiduTest {
Public static void main (String [] args ){
System. out. println (add (6, 2 ));
System. out. println (sub (6, 2 ));
System. out. println (mul (6, 2 ));
System. out. println (div (6, 2 ));
}
Public static int add (int x, int y ){
Return x + y;
}
Public static int sub (int x, int y ){
Return x-y;
}
Public static int mul (int x, int y ){
Return x * y;
}
Public static int div (int x, int y ){
Return x/y;
}
}

//////////////////////////////////////// /////
// 2
Import java. math. BigDecimal;

Public class BaiduTest {
Public static void main (String [] args ){
System. out. println (isRightTriangle (3.0, 4.0, 5.0 ));
}
Public static boolean isRightTriangle (double x, double y, double z ){
BigDecimal bx = new BigDecimal (x );
BigDecimal by = new BigDecimal (y );
BigDecimal bz = new BigDecimal (z );
Bx = bx. pow (2 );
By = by. pow (2 );
Bz = bz. pow (2 );
If (bx. add (by). equals (bz )){
Return true;
}
Return false;
}
}... Remaining full text>

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.