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 details of Java code optimization

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article focuses on "what are the details of Java code optimization", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what are the details of Java code optimization?"

The goal of code optimization is:

Reduce the size of the code

Improve the efficiency of code running

Code optimization details

1. Specify final modifiers for classes and methods as much as possible.

Classes with final modifiers are not derivable. In the core API of Java, there are many examples of using final, such as java.lang.String, where the whole class is final. Assigning a final modifier to a class makes the class uninheritable, and assigning a final modifier to a method makes it impossible for a method to be overridden. If you specify a class as final, all the methods of that class are final. The Java compiler will look for opportunities to inline all final methods, which play an important role in improving the efficiency of Java. For more information, see Java runtime optimization. This can improve performance by an average of 50%.

2. Reuse objects as much as possible

In particular, when using String objects, you should use StringBuilder/StringBuffer instead of string concatenation. Because the Java virtual machine not only takes time to generate objects, it may also take time to garbage collect and process these objects in the future, so generating too many objects will have a great impact on the performance of the program.

3. Use local variables whenever possible

The parameters passed when the method is called and the temporary variables created in the call are saved in the stack faster, while other variables, such as static variables, instance variables, and so on, are created in the heap and are slow. In addition, the variables created in the stack are gone as the method ends, and no additional garbage collection is required.

4. Close the stream in time

In the process of Java programming, you must be careful when you connect to the database and operate the I _ big O stream, and close it in time to release resources after using it. Because the operation of these large objects will cause great overhead of the system, a little carelessness will lead to serious consequences. If conditions permit, that is, above JDK7, it is strongly recommended to use try-with-resources.

5. Minimize the double calculation of variables

Make clear a concept, the call to the method, even if there is only one sentence in the method, there is consumption, including creating stack frames, protecting the scene when the method is called, restoring the site when the method is called, and so on. So for example, do the following:

It is recommended to be replaced by:

It is recommended to be replaced by:

Using shift operation can greatly improve performance, because at the bottom of the computer, alignment operation is the most convenient and fastest, so it is recommended to modify it as follows:

This practice will result in the existence of count Object object references in memory. If the count is very large, memory will be consumed. It is recommended to change to:

At this point, the life cycle of the static variable b is the same as that of class A, and if class An is not unloaded, the B object referenced by B will reside in memory until the program terminates.

18. Timely removal of Session that is no longer needed

To clear inactive sessions, many application servers have a default session timeout of 30 minutes. When the application server needs to save more sessions, if there is not enough memory, the operating system will transfer some of the data to disk, and the application server may dump some inactive sessions to disk according to the MRU (most frequently used recently) algorithm, or even throw an out-of-memory exception. If the session is to be dumped to disk, it must first be serialized, and serialization of objects is expensive in large clusters. Therefore, when the session is no longer needed, the invalidate method of HttpSession should be called in time to clear the session.

19. Collections that implement RandomAccess interfaces, such as ArrayList, should be traversed using the most common for loop instead of the foreach loop

This is recommended by JDK to users. JDK API's interpretation of the RandomAccess interface is that the implementation of the RandomAccess interface is used to show that it supports fast random access. The main purpose of this interface is to allow general algorithms to change its behavior so that it can provide good performance when applied to random or consecutive access lists. Practical experience shows that if the class instance that implements the RandomAccess interface is randomly accessed, it is more efficient to use a normal for loop than to use a foreach loop; conversely, if it is accessed sequentially, it is more efficient to use Iterator. You can make a judgment using code similar to the following:

It is recommended to modify it as follows:

It is judged that "iTunes 1" is not valid, so it is denoted by 0, that is, false. But if:

In this way, even if the developer accidentally writes "1 = I", the CpicCraft + compiler can check it out the first time, because we can assign I to a variable as 1, but not to a constant.

However, in Java, the "if (I = 1)" syntax of CAccord Cure + is impossible, because once the syntax is written, Java compiles the error "Type mismatch: cannot convert from int to boolean". However, although there is no semantic difference between "if (I = = 1)" and "if (1 = = I)" in Java, it is better to recommend the former in terms of reading habits.

30. Do not use the toString method on arrays

Take a look at what is printed using toString on the array:

It is intended to print out the contents of the array, but it is possible to cause a null pointer exception because the array reference is is empty. However, although it makes no sense to the array toString, it is possible to print out the contents of the collection for the collection toString, because the collection's parent class, AbstractCollections, overrides the toString method of Object.

31. Do not make a downward forced transformation of basic data types that are out of range.

This will never get the desired result:

The running result is:

If you just want to traverse the key value of this Map, it would be more appropriate to use "Set keySet = hm.keySet;"

35. Close for resources is recommended to operate separately.

It means, for example, I have this code:

Although there is some trouble, it can avoid the leakage of resources. I think, if there is no modified code, in case XXX.close throws an exception, then it will enter the cath block, YYY.close will not execute, and the resource YYY will not be recycled and will be occupied all the time. If there is too much code like this, it may cause resource handle leakage. After changing to the above method, it is guaranteed that XXX and YYY will be dropped by close anyway. If JDK7 is above, it is strongly recommended to use try-with-resources.

At this point, I believe you have a deeper understanding of "what are the details of Java code optimization?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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