Java code is very practical tips

file

Foreword

Code optimization, a very important issue. Some people may feel useless, some small places there is nothing to modify, change and do not change what impact the efficiency of the code for it? The problem is what I consider, like the sea, like whales inside, it eats a Shrimps useful? Useless, however, after more than one Shrimps eat whale was fed up.

Code optimization is the same, if not the BUG project focusing on line as soon as possible, then the time may encounter, details of the code can not and deliberate; but if there is sufficient time to develop and maintain the code, this time it is necessary to consider each you can optimize the details, and one by one small optimization points accumulated for the efficiency of the code is absolutely upgrade.

Code optimization goal is

1. Reduce the volume of code

2. improve the efficiency of code to run

Code optimization details

1, the class designated as far as possible, the final modifier method

With the final modifier class is not derived. In the Java core API, there are many examples of final applications, such as java.lang.String, the entire class are final. Specify the final qualifier for the class allows the class can not be inherited, designated as ways to make the final modifier methods can not be overridden. If a class as final, the class of all methods are final. Java compiler will look for opportunities within the final with all methods, inline significant role for enhancing the operational efficiency of Java, refer to the specific Java runtime optimization. This can improve the performance by an average of 50%.

2, try to reuse objects

It should be used StringBuilder / StringBuffer place especially if a String object, there is connected the string. Since Java Virtual Machine not only takes time to generate the object, the future may also need to spend time on these objects for garbage collection and disposal, therefore, generate too many objects will bring great impact to the performance of the program.

3, try to use local variables

Delivery method call parameters and temporary variables created in the call are stored in the stack faster, other variables, such as static variables, instance variables, etc., are created on the heap, slower speed. In addition, the stack variables created with the method of operation is completed, the content is gone, no additional garbage collection.

4, close the flow

Java programming, database connections, be careful when I / O stream operations, after use, promptly shut down to release resources. Because of these large objects operation will cause large overhead systems, the slightest mistake will lead to serious consequences.

5, to minimize the double counting of the variables

A clear concept, method calls, even if the method is only one sentence, there are also consumed, including the creation of a stack frame to protect the site when calling the method, the recovery site when finished calling methods. So, for example, the following operations:

file

Recommended alternatives:

file

In this way, list.size () a lot of time, reducing the consumption of a lot

6, lazy loading strategy as far as possible, that is only created when needed

E.g:

file

Recommended alternatives:

file

7, abnormal caution

Abnormal detrimental to performance. An exception is thrown first to create a new object, Throwable constructor function call interface local synchronization method named fillInStackTrace () is, fillInStackTrace () method to check the stack to collect information call tracking. As long as there is an exception is thrown, Java virtual machine must adjust the call stack, because a new object is created in the process. An exception can only be used for error handling, it should not be used to control program flow.

8. Do not try to use in the loop ... catch ..., you should put it on the outermost

Unless a last resort. If for no reason so written, as long as you a little senior leadership, there is a little obsessive-compulsive disorder, most probably you will curse Why write this code to the garbage.

9, if the content length is estimated to be added to the bottom set of an array manner, the tools specify the initial length

Such as ArrayList, LinkedLlist, StringBuilder, StringBuffer, HashMap, HashSet, etc., to StringBuilder example:

(1) StringBuilder () // default space allocation of 16 characters

(2) StringBuilder (int size) // default space allocation size characters

(3) StringBuilder (String str) // default allocation of 16 characters + str.length () characters space

It may be set by the initial capacity class (referred to herein as just above the StringBuilder), which can significantly improve performance. For example StringBuilder bar, length indicates the number of characters in the current StringBuilder can hold. Because the time when StringBuilder reached maximum capacity, it will itself increase the current capacity of 2 plus 2 times, whenever StringBuilder reached its maximum capacity, it will have to create a new character array and then the old character copy the contents of the array to a new array of characters - this is a very cost operational performance. Imagine, if you can estimate the character array to store about 5000 characters without specifying the length of the power of 2 closest to 5000 is 4096, a time of expansion plus 2 regardless, then:

(1) On the basis of the 4096, 8194 and then apply a character array size, add up to the equivalent of a filed 12290 character array size, if a start can specify the size of the character array 5000, saving more than doubled Space;

(2) the original character 4096 copied to the new character to the array.

In this way, a waste of memory space and reduce the efficiency of the code. So, to the underlying array in order to achieve the set of tools to set a reasonable initial capacity is not wrong, it will bring immediate results. However, note that this array as HashMap to achieve the set list is +, do you estimate the initial size and the size of the set, like, just because the possibility of a connection object on a table is almost zero. Recommended to set the initial size N-th power of 2, if it is estimated that there are 2,000 elements provided new HashMap (128), new HashMap (256) may be used.

10, when copying large amounts of data using System.arraycopy () command

11, multiplication and division, for example, using shift operations:

file

The shift operation can greatly improve performance, because in the bottom of the computer, the operating position is the most convenient, fastest, it is proposed amended as follows:

file

Shift operation may be fast, but might make the code less well understood, it is best to add the appropriate comments.

12, the inner loop do not continue to create an object reference

E.g:

file

This practice can lead to memory have copies Object object reference count, count a lot, then it is the cost of memory, it is recommended to read:

file

In this case, only one memory Object object reference, each new Object () when, Object object reference point to different Object nothing, but only a memory, thus greatly save memory space up. Only 13, based on considerations of efficiency and type checking, array should be used as much as possible, we can not determine the size of the array using ArrayList

14, to make use of HashMap, ArrayList, StringBuilder, unless the thread security needs, or do not recommend using Hashtable, Vector, StringBuffer, after three synchronization mechanisms which led to the use of performance overhead

15, do not declare the array as public static final

Because this is meaningless, it just defines a reference for the static final, or the contents of the array can be freely changed, the array is declared as a public security vulnerability, which means that the array can be changed outside the class.

16, as far as possible in the case of a suitable embodiment with a single

Singleton can reduce the burden of load, reduce the time to load and improve the efficiency of the load, but not all places are suitable for a single case, in simple terms, a single case mainly applies to the following three aspects:

(1) control the use of resources, synchronize concurrent access to resources controlled by a thread

(2) generating the control instance in order to save resources

(3) control shared data, at no direct association, so to achieve between multiple processes or threads unrelated communication

17, try to avoid using static random variable

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

file

At this static variable b of the life cycle of the same class A, class A if not uninstalled, then the B object reference point B will be permanent memory, until the program is terminated

18, the timely removal session is no longer needed

To clear the session is no longer active, many application servers have the default session timeout time, usually 30 minutes. When the application server need to preserve more conversation, if insufficient memory, the operating system will transfer part of the data to disk, the application server may also be based on MRU (most recently the most frequently used) algorithm is the part of inactive sessions dump to disk, and may even be thrown out of memory exception. If the session is to be dumped to disk, it must first be serialized, large-scale cluster, an object is serialized costs are very expensive. Therefore, when the session is no longer needed, it should promptly call the HttpSession invalidate () method to clear conversation.

19, a set of interfaces to achieve RandomAccess such as ArrayList, you should use the most common for loop instead of foreach loop to iterate

This is the JDK recommended to the user. JDK API for interpretation RandomAccess interface are: to achieve RandomAccess interface is used to indicate that they support fast random access, the main purpose of this interface is to allow generic algorithms to alter their behavior in order to apply it to a random or sequential access lists can provide a good performance. Practical experience shows RandomAccess interface class instance, if a random access using a normal cycle efficiency will be higher than for using foreach loop; Conversely, if sequential access, the use of higher efficiency will Iterator. Code similar to the following can be determined:file

The principle underlying the foreach loop iterators Iterator, see Java syntax sugar 1: foreach loop variable length parameters and principles. So after the word "Conversely, if it is sequential access, use Iterator will be higher efficiency" means that class instances sequential access, use a foreach loop to iterate.

20, an alternative synchronization method using a synchronization code blocks

This synchronized lock in a multithreaded module in a text block method has been very clear, unless it can determine an entire methods are needed to synchronize, otherwise make use of synchronized block, avoid those that do not require synchronization code also synchronized, affecting the efficiency of code execution.

21, the constant is declared as static final, and in upper case named

Thus during compilation you can put the content into the constant pool, to avoid generating a constant calculated value during operation. In addition, the constant name in uppercase name can easily distinguish between variable and constant

22, do not create some objects do not use, do not import some classes do not use

This is meaningless, if the code appears in "The value of the local variable i is not used", "The import java.util is never used", then please remove these unwanted content

23, the program is running to avoid using reflection

Please see the reflection. Java reflection is to provide the user with a very powerful, powerful often means inefficient. Not recommended, especially the frequent use of reflection in the program is running, especially Method invoke method, if indeed there is necessary a suggestive approach is reflected those classes need to load at the time of project start by reflecting instance of an object and placed in memory - users only get the care and the fastest response time to end the interaction, do not care how long it started to spend time on the end of the project.

24, using a database connection pooling and thread pooling

Both pools are objects for reuse, the former can avoid frequent opening and closing connections, which can avoid frequently create and destroy threads

25, using the buffered input and output streams IO operation

Buffered input and output streams, i.e. BufferedReader, BufferedWriter, BufferedInputStream, BufferedOutputStream, which can greatly enhance the efficiency of IO

26, the order of insertion and more random access scenarios using ArrayList, and delete elements intervening more scenes using this LinkedList, ArrayList and LinkedList understanding of the principles know

27, do not let the public process has too many parameter

Methods public method that is provided externally, if too much parameter to these methods, then there are two main disadvantages:

1, violated the idea of ​​object-oriented programming, Java and stress everything is an object, too many formal parameters, and object-oriented programming ideas do not fit

2, too many parameters will inevitably lead to an increase in error probability method call

As for the "too much" refers to the number, 3,4 bar. For example, we write a insertStudentInfo using JDBC methods, there are 10 fields to be inserted as the student information Student table, these 10 parameters can be encapsulated in an entity class, the insert method as parameter.

28, string variables and string constants equals the time constant string EDITORIAL

This is a relatively common tips, and if there is the following code:

file

Do so mainly to avoid null pointer exception

29, please know that in java if (i == 1) and if (1 == i) there is no difference, but the reading habits of speaking, with the former being

Usually someone asked, "if (i == 1)" and "if (1 == i)" there is no difference, from which C / C ++ talk.

In C / C ++ in, "if (i == 1)" determination condition is satisfied, 0 is the non-zero-based, 0 represents false, nonzero if true, if there is such a code:

file

C / C ++ Analyzing "i == 1" is not satisfied, it represents 0, i.e. false. but if:file

In case a programmer is not careful, the "if (i == 1)" written "if (i = 1)", so there will be problems. If i is within the assigned one, if non-zero determines the contents inside, true is returned, but obviously i is 2, the comparison value is 1, it should return false. In this case the development of C / C ++ in is likely to occur and can lead to some incomprehensible error occurs, so, in order to avoid developers in an if statement incorrect assignment, suggested that if the statement is written as:

file

Thus, even if developers do not accidentally wrote "1 = i", C / C ++ compiler can also check out the first time, because we can be assigned to a variable i is 1, but can not assign a constant 1 i. However, in Java, C / C ++ this syntax "if (i = 1)" is impossible, because once wrote this syntax, Java will compile error "Type mismatch: can not convert from int to boolean . " However, despite Java's "if (i == 1)" and "if (1 == i)" there is no difference in semantics, but the reading habits of speaking, with the former would be better.

30. Do not use the toString () method of the Array

Look at what the array using toString () print out are:

file

The result is:

fileIntention is to print out the contents of the array, there may be empty because the array reference is caused by a null pointer exception. But while () does not make sense for an array toString, but the collection toString () can print out the contents of the collection inside, because the parent AbstractCollections collection of rewrite toString Object () method. 31, do not do down casts the basic data type out of range

This will not get the desired results:

file

We might expect a few of them, but the result is:

file

explain. Java is 8 bytes long in the 64-bit, so 12345678901234 in the computer that should be:

file

Int type is a 4-byte 32-bit, 32-bit is removed from the front above the lower string of binary data is:

file

The string of binary represented as decimal 1,942,892,530, so the content is output on the console above us. In this example also the way to two conclusions:

1, the default data type is an integer int, long l = 12345678901234L, this number is beyond the scope of the int, so there is a final L, it indicates that this is a long type number. By the way, floating-point default type is double, so the definition of float time to write "" float f = 3.5f "

2, then write an "int ii = l + i;" will be given as long + int is a long, int can not be assigned to

32, the common data collection class is not used must be timely remove off

If a collection is public (that is not the way inside the property), then the set of elements inside are not automatically released, because there is always a reference point to them. So, if some of the data does not use public collection inside out rather than to remove them, it will cause the public collection is increasing, so that the system has a memory leak problems.

33, the basic data types into a string of basic data types .toString () is the fastest way, String.valueOf (data), followed by data + "" slowest

The basic data types into a generally three ways, I have a data type Integer i, you can use i.toString (), String.valueOf (i), i + "" three ways, how efficient are three ways to see a test:file

Operating results as follows:file

So we encountered after the basic data types into a String of time, giving priority to the use of toString () method. As for why, it is very simple: 1, String.valueOf () method of the underlying call Integer.toString () method, but before calling the judge will be short

2, Integer.toString () method is not to say, direct call

3, i + "" bottom StringBuilder implemented using a first append method by stitching, and then toString () method takes a string

Comparative down three, obviously 2 fastest, followed by 1, 3 slowest

34, using the most efficient way to traverse Map

There are many ways to traverse Map, usually the scene we need is to traverse the Map Key and Value, it is recommended to use, most efficient way is:

file

If you just want to traverse about this key value Map, then use "Set keySet = hm.keySet ();" Some would be more appropriate

35, to close the resource () is recommended operated separately

Mean, for example, I have such a piece of code:

file

Proposed changes are:

file

Although some trouble, he was able to avoid resource leaks. I think, if not modified code, in case XXX.close () throw an exception, then entered the block in the cath, YYY.close () will not be executed, YYY this resource will not be recovered until occupied with such a code is more than one, is likely to cause resource handle leak. But after the wording was changed to the above, ensures that in any case will be XXX and YYY close out.

                          -------------END-------------复制代码

Xiao Bian recently collected data will be advanced Java programmers architect to do some finishing, free share for every learning Java friends. We need to be into the group: 751 827 870

This article from the blog article multiple platforms OpenWrite release!

Guess you like

Origin juejin.im/post/5dde5697e51d4532e3752fbc
Recommended