Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the programming performance optimization skills of Java programmers?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the programming performance optimization skills of Java programmers". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what are the programming performance optimization skills of Java programmers.

1. Try to use singletons on appropriate occasions

The use of singletons can reduce the burden of loading, shorten the loading time, and improve the efficiency of loading, but it is not applicable to singletons everywhere. To put it simply, singletons are mainly applicable to the following three aspects:

Control the use of resources, control the concurrent access of resources through thread synchronization, control the generation of instances to achieve the purpose of saving resources, and control data sharing without establishing a direct correlation. Enable communication between multiple unrelated processes or threads.

two。 Try to avoid the random use of static variables

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

At this point, the life cycle of the static variable b is synchronized with class A, and if class A does not unload, then the b object will reside in memory until the program terminates.

3. Try to avoid creating Java objects too often.

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

4. Use final modifiers whenever possible

Classes with final modifiers are not derivable. In the JAVA core API, there are many examples of using final, such as java.lang.String, where specifying final for the String class prevents users from overriding the length method. In addition, if a class is final, then all methods of that 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 improve performance by an average of 50%.

For example, change the getter/setter method that accesses variables in the instance to "final:

The simple getter/setter method should be set to final, which tells the compiler that the method will not be overloaded, so it can be changed to "inlined", for example:

5. Use local variables as much as possible

The parameters passed when the method is called and the temporary variables created in the call are stored in the Stack, which is faster. Other variables, such as static variables, instance variables, and so on, are created in the Heap and are slow.

6. Try to deal with the use of both packaging types and basic types.

Although the wrapper type and the basic type can be converted to each other in the process of use, the memory areas generated by them are completely different, the basic type data generation and processing are processed in the stack, and the wrapper type is an object. Is to generate an instance in the heap. In the collection class object, the wrapper type is applicable to the processing needed for the object, and the basic type is advocated for other processing.

7. Use synchronized cautiously and minimize synchronize

As we all know, the realization of synchronization takes a lot of system overhead as a price, and may even cause deadlock, so try to avoid unnecessary synchronization control. When the synchronize method is called, the current object is locked directly, and other threads cannot call other methods of the current object until the method is executed. So the method of synchronize is as small as possible, and you should try to use method synchronization instead of code block synchronization.

8. Try not to use the finalize method

In fact, it is a very bad choice to clean up resources in the finalize method. Because of the heavy workload of GC, especially when reclaiming Young generation memory, it will mostly cause applications to pause, so choosing to use the finalize method for resource cleaning will lead to a greater burden on GC and less efficient programs.

9. Try to use basic data types instead of objects

String str = "hello"

The above method creates a "hello" string, and JVM's character cache pool also caches the string

String str = new String ("hello")

At this time, in addition to creating strings, the bottom layer of the String object referenced by str also contains a char array, which in turn stores the char array.

10. Multithreads should try their best to use HashMap and ArrayList without thread safety.

HashTable, Vector and so on use synchronization mechanism, which degrades the performance.

11. Create HashMap as reasonably as possible

When you want to create a larger hashMap, take full advantage of this constructor

To prevent HashMap from doing hash refactoring many times, capacity expansion is a very performance-consuming thing. By default, initialCapacity is only 16, while loadFactor is 0.75. how much capacity you need, you'd better accurately estimate the optimal size you need, and the same is true for Hashtable,Vectors.

twelve。 Minimize the double calculation of variables

It should be changed to

And the use of complex expressions should be avoided in the loop. In the loop, the loop condition will be calculated repeatedly. If the complex expression is not used and the loop condition value is kept unchanged, the program will run faster.

13. Try to release resources in the finally block

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

14. Try to use shift instead of the operation of'a _ gamb'

"/" is a costly operation, and using shift will be faster and more efficient.

15. Try to determine the capacity of StringBuffer

StringBuffer's constructor creates an array of characters of the default size (usually 16). In use, if this size is exceeded, memory is reallocated, a larger array is created, the original array is copied, and the old array is discarded. In most cases, you can specify the size when you create the StringBuffer, which avoids automatic growth when there is not enough capacity to improve performance.

16. Release references to useless objects as early as possible

Most of the time, the object referenced by the method local reference variable becomes garbage as the method ends, so most of the time the program does not need to explicitly set the local reference variable to null. For example:

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

At this point, it is necessary to assign obj to null so that the reference to the Object object can be released as soon as possible.

17. Avoid using two-dimensional arrays as much as possible

Two-dimensional data takes up much more memory space than an one-dimensional array, about 10 times more.

18. Avoid using split as much as possible

Unless necessary, you should avoid using split,split because it supports regular expressions, so it is inefficient. If it is dozens of times, 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). Frequent split can cache the results.

19.ArrayList & LinkedList

One is a linear table, one is a linked list, in a word, random queries try to use ArrayList,ArrayList better than LinkedList,LinkedList but also move the pointer, add and delete operation LinkedList is better than ArrayList,ArrayList but also move data, but this is a theoretical analysis, this may not be the case, it is important to understand the data structure of the two, the right remedy to the case.

20. Try to use System.arraycopy instead of cyclically copying arrays by

System.arraycopy is much faster than copying an array through a loop

21. Cache frequently used objects as much as possible

Caching frequently used objects as much as possible, you can use arrays or HashMap containers for caching, but this approach may lead to excessive cache consumption and performance degradation. It is recommended to use some third-party open source tools, such as EhCache,Oscache for caching, which basically implement caching algorithms such as FIFO/FLU.

twenty-two。 Try to avoid very large memory allocation

Sometimes the problem is not caused by the heap state at that time, but by the allocation failure. Allocated memory blocks must be contiguous, and as the heap becomes more and more full, it becomes more and more difficult to find larger contiguous blocks.

23. Use anomalies with caution

When you create an exception, you need to collect a stack trace (stack track) that describes where the exception was created. Building these stack traces requires a snapshot of the runtime stack, which is expensive. When you need to create an Exception, JVM has to say: don't move, I want to save a snapshot of what you are now, so stop stack-in and out-stack operations for the time being. The stack trace contains not only one or two elements in the runtime stack, but every element in the stack.

If you create an Exception, you have to pay a price. Fortunately, catching exceptions is inexpensive, so you can use try-catch to wrap the core content. Technically, you can even throw exceptions at will without having to spend a lot of money. It is not throw operations that incur performance losses-although it is a bit unusual to throw an exception without creating an exception in advance. What really costs is creating an exception. Fortunately, good programming habits have taught us that exceptions should not be thrown regardless of the circumstances. Exceptions are designed for exceptional situations, and you should keep this principle in mind when using them.

24. Reuse objects as much as possible

Especially in the use of String objects, StringBuffer should be used instead of string concatenation, because the system not only takes time to generate objects, but may also take time to garbage collect and dispose of these objects in the future. So generating too many objects will have a great impact on the performance of the program.

25. Do not repeat initialization variables

By default, when calling the constructor of a class, java initializes the variable 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 logical values are set to false. This is especially important when a class derives from another class, because when you create an object with the new keyword, all constructors in the constructor chain are called automatically.

Here is a note. When you set an initial value for a member variable but need to call another method, it is best to put it in a method such as initXXX, because calling a method assignment directly may cause a pointer exception to be thrown because the class has not been initialized, such as: public int state = this.getState

twenty-six。 In the development of java+Oracle application system

In the development of java+Oracle application system, the SQL language embedded in java should use uppercase as much as possible to reduce the parsing burden of Oracle parser.

27.I/O stream operation

In the process of java programming, the database connection is carried out, and the Imax O stream operation is carried out. After the use is finished, it is closed in time to release resources. Because the operation on these large objects will cause great overhead to the system.

twenty-eight。 Creating objects consumes a lot of memory in the system.

Excessive creation of objects will consume a lot of memory of the system, and in serious cases, it will lead to memory leaks. Therefore, it is of great significance to ensure the timely collection of expired objects. The GC of JVM is not very smart, so it is recommended that you manually set it to null after the object has been used.

twenty-nine。 When using the synchronization mechanism

When using synchronization mechanisms, you should try to use method synchronization instead of code block synchronization.

thirty。 Do not use Try/ catch statements in the loop, put Try/Catch on the outermost layer of the loop

Error is the class that gets system errors, or virtual machine errors. Not all error Exception can be obtained, virtual machine error Exception can not be obtained, must be obtained with Error.

thirty-one。 The performance can be significantly improved by setting its initialization capacity through the constructor of StringBuffer.

The default capacity of StringBuffer is 16, and when StringBuffer reaches its maximum capacity, she will increase her capacity to twice the current capacity + 2, that is, 2*n+2. Whenever StringBuffer reaches her maximum capacity, she has to create a new array of objects and then copy the old array of objects, which wastes a lot of time. So it is necessary to set a reasonable initialization capacity value for StringBuffer!

thirty-two。 Rational use of java.util.Vector

Vector is similar to StringBuffer in that each time you expand capacity, all existing elements are assigned to the new storage space. The default storage capacity of Vector is 10 elements, which is doubled by expansion.

The vector.add (index,obj) method inserts the element obj into the index position, but the index and subsequent elements move down one position in turn (add its index by 1). Unless necessary, it is bad for performance. The same rule applies to the remove (int index) method, which removes the element at the specified location in this vector. Move all subsequent elements to the left (subtract their index by 1). Returns the elements removed from this vector. So deleting the last element of vector is much less expensive 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 vector, you can use vector.remove (obj); instead of having to retrieve the element location yourself, delete it, such as int index = indexOf (obj); vector.remove (index)

thirty-three。 Create an instance of an object without the new keyword

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

Here is a typical implementation of the Factory pattern:

Traversal of 34.HaspMap

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

Thank you for your reading, the above is the "Java programmer programming performance optimization skills what are" the content, after the study of this article, I believe you have a deeper understanding of what Java programmer programming performance optimization skills have a deeper understanding, the specific use of the need for you to practice and verify. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report