How to optimize Java programming and coding to improve performance (recommended collection)

1. Try to use singletons in suitable occasions

Using singletons can reduce the burden of loading, shorten loading time, and improve loading efficiency, but not all places are suitable for singletons. In short, singletons are mainly suitable for the following three aspects:

First, control the use of resources, and control the concurrent access of resources through thread synchronization;

Second, control the generation of instances to achieve the purpose of saving resources;

Third, control data sharing and allow multiple unrelated processes or threads to communicate without establishing direct associations.

2. Try to avoid random use of static variables

You know, when an object is defined as referenced by a static variable, the GC usually does not reclaim the memory occupied by this object, such as:

At this time, the life cycle of static variable b is synchronized with class A. If class A will not be unloaded, then the b object will stay in memory until the program terminates.

3. Try to avoid creating Java objects too often

Try to avoid new objects in frequently called methods and loops, because the system not only takes time to create objects, but also takes time to garbage collect and process these objects, so as to maximize the reuse of objects within our control. , It is best to replace objects with basic data types or arrays.

How to optimize Java programming and coding to improve performance (recommended collection)

 

4. Try to use final modifiers

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

Such as: make the getter/setter method of accessing variables in the instance become "final:

A simple getter/setter method should be set to final, which will tell the compiler that this method will not be overloaded, so it can become "inlined", for example:

How to optimize Java programming and coding to improve performance (recommended collection)

 

5. Try to use local variables

The parameters passed when the method is called and the temporary variables created in the call are saved in the stack, which is faster. Other variables, such as static variables, instance variables, etc., are created in the heap, which is slower.

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

Although the packaging type and the basic type can be converted to each other during use, the memory area generated by the two is completely different. The basic type data generation and processing are processed in the stack, and the packaging type is an object, which is in the heap. Produce examples. For collection objects, packaging types are applicable to the processing required by the object, and basic types are recommended for other processing.

7. Use synchronized with caution, minimize the method of synchronize

As we all know, the realization of synchronization will cost a lot of system overhead, and may even cause deadlock, so try to avoid unnecessary synchronization control. When the synchronize method is called, the current object is directly locked, and other threads cannot call other methods of the current object before the method is executed. Therefore, the method of synchronize is as small as possible, and method synchronization should be used instead of code block synchronization.

8. Try not to use the finalize method

In fact, it is a very bad choice to put the resource cleanup in the finalize method. Due to the large workload of the GC, especially when the Young generation memory is recycled, the application will be suspended, so choose to use the finalize method for resources Cleaning up will cause a greater burden on the GC and worse program operation efficiency.

9. Try to use basic data types instead of objects

String str = “hello”;

The above method will create a "hello" string, and the character buffer pool of the JVM will also cache this string;

String str = new String(“hello”);

At this time, in addition to creating a string, the bottom layer of the String object referenced by str also contains a char array, which in turn stores h, e, l, l, o

How to optimize Java programming and coding to improve performance (recommended collection)

 

10. Multithreading should try to use HashMap and ArrayList without thread safety

HashTable, Vector, etc. use a synchronization mechanism, which reduces performance.

11. Create HashMap as reasonably as possible

When you want to create a relatively large hashMap, make full use of this constructor

Avoid HashMap’s hash reconstruction many times. Expansion is a very performance-consuming thing. By default, the initialCapacity is only 16, and the loadFactor is 0.75. How much capacity is needed, you'd better be able to accurately estimate the best you need Size, the same Hashtable, Vectors is the same reason.

12. Minimize double counting of variables

Such as: should be changed to

And avoid using complex expressions in loops. In loops, loop conditions will be repeatedly calculated. If complex expressions are not used and the loop condition values ​​remain unchanged, the program will run faster.

13. Try to avoid unnecessary creation

Such as: should be changed to

14 Try to release resources in the finally block

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

15. Try to use shifts instead of'a/b' operations

"/" is a costly operation, the operation using shift will be faster and more effective

16. Try to determine the capacity of StringBuffer

The StringBuffer constructor creates a character array of default size (usually 16). In use, if this size is exceeded, the memory will be reallocated, 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 not enough to improve performance.

17. Release references to useless objects as early as possible

Most of the time, the object referenced by the method local reference variable will become garbage as the method ends. Therefore, most of the time the program does not need to explicitly set the local reference variable to null. E.g:

How to optimize Java programming and coding to improve performance (recommended collection)

 

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

How to optimize Java programming and coding to improve performance (recommended collection)

 

At this time, it is necessary to assign obj to null to release the reference to the Object object as soon as possible.

18. Try to avoid using two-dimensional arrays

Two-dimensional data occupies much more memory space than one-dimensional data, probably more than 10 times.

19. Try to avoid using split

Unless it is necessary, you should avoid using split. Split is relatively inefficient because it supports regular expressions. If it is frequent dozens of calls, millions of calls will consume a lot of resources. If you really need to call split frequently, you can Consider using apache's StringUtils.split(string,char), the results of frequent splits can be cached.

20.ArrayList & LinkedList

One is a linear table and the other is a linked list. In a word, try to use ArrayList for random queries. ArrayList is better than LinkedList. LinkedList also needs to move pointers. Adding and deleting operations LinkedList is better than ArrayList. ArrayList also needs to move data. But this is a theoretical analysis. , The fact is not necessarily the case, the important thing is to understand the data structure of the two and prescribe the right medicine.

21. Try to use System.arraycopy instead of looping to copy arrays

System.arraycopy is much faster than copying arrays through loops

22. Try to cache frequently used objects

Cache frequently used objects as much as possible. You can use arrays or HashMap containers for caching, but this method may cause the system to occupy too much cache and reduce performance. It is recommended to use some third-party open source tools, such as EhCache , Oscache performs caching, and they basically implement caching algorithms such as FIFO/FLU.

23. Try to avoid very large memory allocations

Sometimes the problem is not caused by the current state of the heap, but by the allocation failure. All allocated memory blocks must be contiguous, and as the heap becomes fuller, it becomes more and more difficult to find larger contiguous blocks.

24. Use exceptions with caution

When creating an exception, you need to collect a stack track, which is used to describe where the exception was created. When building these stack traces, you need to take a snapshot of the runtime stack, which is very expensive. When you need to create an Exception, the JVM has to say: Don't move, I want to save a snapshot of your current state, so temporarily stop the stacking and popping operations. The stack trace contains not only one or two elements in the runtime stack, but each element in the stack.

If you create an Exception, you have to pay the price. Fortunately, catching exceptions is not expensive, so try-catch can be used to wrap the core content. Technically, you can even throw exceptions at will, without spending a lot of money. It is not the throw operation that incurs the performance loss-although it is a bit unusual to throw an exception without creating it in advance. The real price is to create exceptions. Fortunately, good programming habits have taught us that we shouldn't throw exceptions regardless of the facts. Exceptions are designed for abnormal situations, and this principle should also be kept in mind when using them.

How to optimize Java programming and coding to improve performance (recommended collection)

 

25. Reuse objects as much as possible

Especially in the use of String objects, StringBuffer should be used instead when string connection occurs. Because the system not only takes time to generate objects, it may also take time to garbage collect and process these objects in the future. Therefore, generating too many objects will have a great impact on the performance of the program.

26. Don't re-initialize variables

By default, when calling the constructor of the class, Java will initialize the variables to a certain value, all objects are set to null, integer variables are set to 0, float and double variables are set to 0.0, and the logical value is set to false. This should be especially noted when a class is derived from another class, because when an object is created with the new keyword, all constructors in the constructor chain will be automatically called.

There is a note here. When you set the initial value of a member variable but need to call other methods, it is best to put it in a method such as initXXX, because directly calling a method assignment may throw a null pointer exception because the class has not been initialized, such as: public int state = this.getState;

27. In the development of java+Oracle application system

In the development of java+Oracle application system, the SQL language embedded in java should be capitalized as much as possible to reduce the analysis burden of the Oracle parser.

28. I/O stream operations

In the process of java programming, database connection and I/O stream operations are performed. After use, it is closed in time to release resources. Because the operation of these large objects will cause system overhead.

29. Creating objects consumes a lot of system memory

Excessive creation of objects will consume a large amount of memory in the system, and in severe cases, it will cause memory leaks. Therefore, it is important to ensure the timely recovery of expired objects. JVM's GC is not very smart, so it is recommended to manually set to null after the object is used.

30. When using synchronization mechanisms

When using the synchronization mechanism, try to use method synchronization instead of code block synchronization.

31. Do not use Try/Catch statement in the loop, try/Catch should be placed in the outermost layer of the loop

Error is a class for obtaining system errors, or a class for virtual machine errors. Not all error Exception can be obtained, and the virtual machine will not get the error Exception. You must use Error to obtain it.

32. Set its initial capacity through the StringBuffer constructor, which can significantly improve performance

The default capacity of StringBuffer is 16. When the capacity of StringBuffer reaches the maximum capacity, it will increase its own capacity to 2 times+2 of the current, which is 2*n+2. Whenever the StringBuffer reaches its maximum capacity, she has to create a new object array and then copy the old object array, which will waste a lot of time. So it is necessary to set a reasonable initial capacity value for StringBuffer!

How to optimize Java programming and coding to improve performance (recommended collection)

 

33. Use java.util.Vector reasonably

Vector is similar to StringBuffer. Every time the capacity is expanded, all existing elements must be assigned to the new storage space. The default storage capacity of Vector is 10 elements, and the expansion is doubled.

vector.add(index,obj) This method can insert the element obj into the index position, but the index and the following elements must be moved down one position in turn (the index is increased by 1). Unless necessary, it is detrimental to performance. The same rule applies to the remove(int index) method, which removes the element at the specified position in this vector. Shift all subsequent elements to the left (minus their index by 1). Returns the elements removed from this vector. So deleting the last element of the vector is much cheaper than deleting the first element. It is best to use the removeAllElements method to delete all elements.

If you want to delete an element in a vector, you can use vector.remove(obj); instead of retrieving the position of the element yourself, delete it again, such as int index = indexOf(obj); vector.remove(index);

34. Create object instances without the new keyword

When creating an instance of a class with the new keyword, all constructors in the constructor chain will be automatically called. But if an object implements the Cloneable interface, we can call her clone method. The clone method does not call any class constructors.

The following is a typical implementation of the Factory pattern:

How to optimize Java programming and coding to improve performance (recommended collection)

 

35.HaspMap traversal

Use the hash value to take out the corresponding Entry for comparison to get the result, and get the key and value directly after obtaining the value of the entry.

Guess you like

Origin blog.csdn.net/sinat_37903468/article/details/108814061