In Java programming, we try to do some things for the sake of performance.

Source: Internet
Author: User
Tags finally block

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

  • Public Class {
  • Static B = new B ();
  • }


Public Class A {static B = new B ();}
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.

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

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 and arraylist as much as possible for a single thread

Hashtable and vector use synchronization mechanisms to reduce performance.

12. Create a hashmap as reasonably as possible

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 ();}

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 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

  • Public void test (){
  • Object OBJ = new object ();
  • ......
  • OBJ = NULL;
  • }


Public void test () {object OBJ = new object ();...... OBJ = NULL ;}
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

  • Public void test (){
  • Object OBJ = new object ();
  • ......
  • OBJ = NULL;
  • // Execution time-consuming, memory-consuming, or calling time-consuming, memory-consuming Methods
  • ......
  • }


Public void test () {object OBJ = new object ();...... OBJ = NULL; // time-consuming and memory-consuming operations for execution; or calling time-consuming and memory-consuming methods ......}

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. Avoid using split whenever possible

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 linear list, and the linear list must be moved to the specified needle, 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.

Reply:
Wrote xuanyuan
7. Use synchronized with caution to minimize synchronize.
Re: Yes, but there is a mistake in this article. Using the synchronized keyword may not always lock the current object. It depends on the specific lock. If synchronized is added to a method, the object itself is the lock. If it is a static method, the lock granularity is a class.
---------------
9. Try not to use the Finalize method
Re: Yes. In fact, we do not recommend using the Finalize method because the JVM specification does not guarantee the time to execute this method. Therefore, it is inappropriate to use this method to release resources, it is possible that resources cannot be released for a long time.
---------------
16. Use shift as much as possible to replace the operation of 'a/B '. 17. Use shift as much as possible to replace the operation of 'a * B '.
Re: I do not agree with the two. This does have better performance, but it sacrifices readability. These two operators are not intuitive to many programmers. I think it is a good choice to sacrifice some performance slightly when the current hardware price is not so expensive, in order to improve readability and maintainability.

Wuzhengju wrote
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:
Public void test (){
Object OBJ = new object ();
......
OBJ = NULL;
}
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:
Public void test (){
Object OBJ = new object ();
......
OBJ = NULL;
// Execution time-consuming, memory-consuming, or calling time-consuming, memory-consuming Methods
......
}
If object OBJ = new object (); if this object is not a large object, is this necessary? OBJ = NULL; it only tells the JVM that the object has become garbage. It cannot be determined when to recycle it! This is not readable!

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.