This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

In my opinion, the most important function of code optimization is to avoid unknown errors. There are a lot of unexpected errors that occur when code is up and running, and because the online environment and the development environment are very different, it’s usually a very small cause.

However, in order to resolve this error, we need to self-validate, package out the class file to be replaced, suspend the service, and restart the application. For a mature project, the last one actually has a significant impact, meaning that users cannot access the application during this time.

Therefore, when writing code, paying attention to details from the source, weighing and using the best options, will largely avoid unknown errors and greatly reduce the amount of work done in the long run.

The goals of code optimization are:

  • Reduce the size of the code

  • Improve the efficiency of code execution

Some of the content in this article comes from the Internet, and some comes from work and study. Of course, it doesn’t matter. What matters is whether the details of code optimization are actually useful. This article will be updated regularly, as soon as it encounters code optimization details worth sharing.

Code optimization details

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

Classes with the final modifier are not derivable. In the Java core API, there are many examples of final applications, such as java.lang.String, where entire classes are final. Specifying a final modifier for a class makes it uninheritable, and specifying a final modifier for a method makes it unoverridden.

If a class is specified as final, all methods of that class are final. The Java compiler looks for opportunities to inline all final methods. Inlining is important for improving Java runtime efficiency. See Java Runtime Optimization. This can improve performance by an average of 50%.

Reuse objects as much as possible

Especially the use of String object, there should use StringBuilder/StringBuffer instead of String concatenation. Because the Java virtual machine takes time not only to generate objects, but also to garbage collect and dispose of them later, generating too many objects can have a significant impact on your program’s performance.

3. Use local variables whenever possible

Parameters passed when a method is called, as well as temporary variables created during the call, are kept in the stack faster, while other variables, such as static variables, instance variables, and so on, are created in the heap slower. In addition, variables created in the stack are removed as the method completes its run, requiring no additional garbage collection.

4. Close the stream in time

During Java programming, be careful when connecting to the database and performing I/O flow operations. After using the database, close the database to release resources. Because the operation of these large objects will cause a large overhead of the system, a slight mistake will lead to serious consequences.

5. Minimize the double calculation of variables

Make it clear that calls to a method, even if there is only one statement in the method, have costs, including creating stack frames, protecting the scene when the method is called, and restoring the scene when the method is finished. So for example:

for (int i = 0; i < list.size(); i++) {… }

You are advised to replace it with:

for (int i = 0, length = list.size(); i < length; i++) {… }

This saves a lot of overhead when list.size() is large

6. Try to use a lazy loading strategy, that is, create it when you need it

Such as:

String str = "aaa"; If (I == 1) {list.add(STR); }Copy the code

You are advised to replace it with:

If (I == 1) {String STR = "aaa"; list.add(str); }Copy the code

7. Use exceptions with caution

Exceptions are detrimental to performance. To throw an exception, a new object is created. The constructor of the Throwable interface calls a locally synchronized method called fillInStackTrace(), which checks the stack to collect the call trace information.

Whenever an exception is thrown, the Java virtual machine must adjust the call stack because a new object is created during processing. Exceptions should only be used for error handling and should not be used to control program flow.

8. Do not use try… The catch… You should put it in the outermost layer

According to the opinions put forward by the netizens, this point I think is worth discussing, welcome everyone to put forward views!

9. If you can estimate the length of the content to be added, specify the initial length for the underlying array-based collections and utility classes

Examples include ArrayList, LinkedLlist, StringBuilder, StringBuffer, HashMap, HashSet, etc. Take StringBuilder for example:

StringBuilder()// The default space to allocate 16 characters StringBuilder(int size)// The default space to allocate 16 characters

StringBuilder(String STR)// Default allocation of 16 characters +str.length() character space

You can set the initialization capacity of a class (and not just the StringBuilder above) through its constructor, which can significantly improve performance. For example, StringBuilder, length is the number of characters that the current StringBuilder can hold.

Because when StringBuilder reaches its maximum capacity, it increases its current capacity by two plus two, and whenever StringBuilder reaches its maximum capacity, It has to create a new character array and copy the contents of the old character array into the new character array —- which is a very performance expensive operation.

Imagine that the array contains about 5000 characters without specifying the length, and the nearest power of 5000 is 4096, with each increment incrementing by 2: Applying for 8194 character arrays on top of 4096 adds up to applying for 12290 character arrays at once, more than doubling the space saved if you could have specified 5000 character arrays initially

Copying 4096 characters into the new character array wastes memory and reduces code efficiency. Therefore, you can’t go wrong with setting a reasonable initialization capacity for collections and utility classes that are implemented in arrays at the bottom. This will bring immediate results.

Note, however, that for collections such as a HashMap, which is implemented as an array + linked list, do not set the initial size to the size you estimated, because the probability of joining only one object on a table is almost zero. The recommended initial size is 2 to the NTH power, or new HashMap(128) or new HashMap(256) if 2000 elements are expected.

10. Run the system.arraycopy () command to copy a large amount of data

Multiplication and division use shift operations

Such as:

for (val = 0; val < 100000; Val += 5) {a = val * 8; b = val / 2; }Copy the code

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

for (val = 0; val < 100000; Val += 5) {a = val << 3; b = val >> 1; }Copy the code

The shift operation, while fast, can make the code difficult to understand, so it is best to comment accordingly.

12. Do not keep creating object references within the loop

Such as:

for (int i = 1; i <= count; i++)	
{	
    Object obj = new Object();    	
}
Copy the code

If count is too large, the memory will be used. We recommend changing it to:

Object obj = null;	
for (int i = 0; i <= count; i++)	
{	
    obj = new Object();	
}	
Copy the code

Each time a new Object() is called, the Object reference refers to a different Object, but there is only one Object in memory. This saves a lot of memory.

13. For efficiency and type checking purposes, use arrays whenever possible, and use ArrayList only when the size of the array is uncertain

Use HashMap, ArrayList, and StringBuilder as much as possible. Hashtable, Vector, and StringBuffer are not recommended unless thread-safe because they incur performance overhead due to synchronization

Do not declare arrays to be public static final

Declaring an array public is a security loophole, which means that the array can be changed by an external class

16, try to use singletons in appropriate situations

Singletons can reduce the load burden, shorten the load time, and improve the load efficiency. However, they are not applicable to all places. In brief, singletons are mainly applicable to the following three aspects:

  • Control the use of resources, through thread synchronization to control concurrent access to resources

  • Control the generation of instances to achieve the purpose of saving resources

  • Control the sharing of data and allow communication between unrelated processes or threads without establishing a direct correlation

17. Avoid arbitrary use of static variables

Remember that when an object is referenced by a variable defined as static, gc usually does not reclaim the heap memory occupied by the object, as in:

public class A {	
    private static B b = new B();  	
}
Copy the code

The lifetime of the static variable B is the same as that of class A. If class A is not unloaded, the object referred to by b will stay in memory until the program terminates

18. Clear up sessions that are no longer needed

To clear out inactive sessions, many application servers have a default session timeout, typically 30 minutes. When the application server needs to hold more sessions, if the memory is low, the operating system will move some of the data to disk, the application server may dump some of the inactive sessions to disk according to the MRU (most frequently used recently) algorithm, or even throw an out-of-memory exception.

If a session is to be dumped to disk, it must first be serialized, and serializing objects can be expensive in a large cluster. Therefore, when a session is no longer needed, it should be immediately cleared by calling the invalidate() method of HttpSession.

19. Collections that implement the RandomAccess interface, such as ArrayList, should be traversed using the most common for loop rather than the foreach loop

This is what the JDK recommends to users. The RandomAccess interface is implemented to show that it supports fast RandomAccess. The main purpose of this interface is to allow general algorithms to change their behavior to provide good performance when applied to random or continuously accessed lists.

Practical experience shows that the efficiency of using ordinary for loop is higher than foreach loop if the class instance implementing RandomAccess interface is accessed randomly. Conversely, if the access is sequential, it is more efficient to use Iterator.

This can be done with code like the following:

if (list instanceof RandomAccess) { for (int i = 0; i < list.size(); i++){} } else { Iterator<? > iterator = list.iterable(); while (iterator.hasNext()) { iterator.next() } }Copy the code

The underlying implementation principle for foreach loops is the Iterator. See Java Syntax Sugar 1: Variable-length Arguments and Foreach loops. Instead, it is more efficient to use Iterator if the class is accessed sequentially.

Use synchronized code blocks instead of synchronized methods

This point has been clearly stated in the article of synchronized lock method block in multi-threaded module. Unless it can be determined that a whole method needs to be synchronized, it should try to use synchronized code block to avoid the synchronization of those codes that do not need to be synchronized, which affects the efficiency of code execution.

21. Declare constants static final and name them in uppercase

This allows you to put the content into the constant pool at compile time, avoiding the need to evaluate the value of the generated constant at run time. In addition, it is easy to distinguish constants from variables by naming them in uppercase

Don’t create some unused objects, don’t import some unused classes, it makes no sense

If “The value of The local variable I is not used”, “The import java.util is never used”, delete these useless contents.

23. Avoid the use of reflection during program operation

For more information, see Reflection. Reflection is a powerful feature that Java provides to users, and powerful features often mean inefficient. It is not recommended to use reflection during program execution, especially when it is used frequently, especially with Method’s Invoke Method.

If necessary, it is recommended that classes that need to be loaded by reflection instantiate an object and put it into memory at project startup —- The user is only interested in getting the fastest response when interacting with the other end, not how long it takes the other end to start the project.

24. Use database connection pools and thread pools

Both pools are designed to reuse objects, the former to avoid frequent opening and closing of connections, and the latter to avoid frequent thread creation and destruction

Use buffered INPUT/output streams for IO operations

Buffered input and output streams (BufferedReader, BufferedWriter, BufferedInputStream, BufferedOutputStream) can greatly improve I/O efficiency

26. Use ArrayList for sequential inserts and random access scenarios

Element deletion and intercalation scenarios use LinkedList. Understand ArrayList and LinkedList

27. Don’t let public methods have too many parameters

Public methods, that is, methods provided externally, have two main disadvantages if they are given too many parameters:

  • It violates the idea of object-oriented programming, because Java insists that everything is an object, and too many parameters, and object-oriented programming doesn’t fit

  • Too many parameters will inevitably increase the probability of error in method calls

As for how many by “too many” I mean, three or four. For example, if we write an insertStudentInfo method in JDBC and have 10 Student fields to insert into the Student table, we can wrap these 10 parameters in an entity class as parameters to the insert method

28, String variables and string constants equals before string constants

This is a very common trick,

If you have the following code:

String str = "123";	
if (str.equals("123")) {	
    ...	
}
Copy the code

You are advised to change the value to:

String str = "123";	
if ("123".equals(str)) {	
    ...	
}
Copy the code

This is mostly to avoid null-pointer exceptions.

29, If (I == 1) is the same as if (1 == I) in Java.

If (I == 1) is different from if (1== I). If (I == 1) is different from if (1== I).

In C/C++, if (I == 1) is true, based on 0 and non-0, 0 means false, non-0 means true, if there is such a code:

int i = 2;	
if (i == 1) {	
    ...	
} else {	
    ...	
}
Copy the code

C/C++ determines that I ==1 is not true, so it is represented by 0, i.e. False. But if:

int i = 2;	
if (i = 1) {	
    ...	
} else {	
    ...	
}
Copy the code

If a programmer accidentally writes if (I == 1) as if (I = 1), then there’s a problem. If (I = 1); if (I = 1); if (I = 1);

This can happen in C/C++ development and can lead to some unintelligible errors, so to avoid incorrect assignments in if statements, it is recommended to write if statements as:

int i = 2;	
if (1 == i) {	
    ...	
	
} else {	
    ...	
}
Copy the code

This way, even if the developer accidentally writes 1 = I, the C/C++ compiler can detect it in the first place because we can assign I to a variable, but not to a constant.

Type Mismatch: Cannot convert from int to Boolean Type Mismatch: Cannot convert from int to Boolean However, although there is no semantic difference between Java if (I == 1) and if (1 == I), the former is better recommended as a matter of reading habit.

30. Do not use the toString() method on arrays

Take a look at what is printed using toString() on an array:

public static void main(String[] args) {	
    int[] is = new int[]{1, 2, 3};	
    System.out.println(is.toString());	
}
Copy the code

The result is:

[I@18a992f

The null pointer exception is possible because the array reference is null. AbstractCollections overrides the toString() method of Object, but it doesn’t make sense to print the contents of the collection toString().

31. Do not force downcasts of basic data types that are out of scope

This will never get the desired result:

public static void main(String[] args) {	
    long l = 12345678901234L;	
    int i = (int)l;	
    System.out.println(i);	
}
Copy the code

We might expect some of them, but the result is:

1942892530

Explain. In Java, long is 8 bytes 64-bit, so 12345678901234 should look like this:

0000 0000 0000 0000 0000 1011 0011 1010 0111 0011 1100 1110 0010 1111 1111 0010

The first 32 bits of an int are the same as the first 32 bits of an int:

0111 0011 1100 1110 0010 1111 1111 0010

This string of binary is represented as decimal 1942892530, so that’s what our console output is above. Two further conclusions can be drawn from this example:

The default data type for integers is int, long l = 12345678901234L. This number is outside the scope of int, so there is an L at the end to indicate that this is a long number. By the way, the default floating-point type is double, so you define float as float f = 3.5f

And then int ii = l + I; An error is reported because long + int is a long and cannot be assigned to int

Public collection classes do not use data, be sure to remove in time

If a collection class is public (that is, not an attribute in a method), the elements in the collection are not automatically freed because there are always references to them. Therefore, if some data in the public set is not used but not removed, it will cause the public set to increase, so that the system has the potential of memory leakage.

Convert a primitive data type to a string

Basic data type. ToString () is the fastest, string.valueof (data) is the next, and ** data +”” is the slowest. ** There are three ways to convert a basic data type to a String. I have an Integer data type I, and I can use i.tostring (), string.valueof (I), and I +””.

public static void main(String[] args) { int loopTime = 50000; Integer i = 0; long startTime = System.currentTimeMillis(); for (int j = 0; j < loopTime; j++) { String str = String.valueOf(i); } system.out.println (" string.valueof () : "+ (system.currentTimemillis () -startTime) + "ms"); startTime = System.currentTimeMillis(); for (int j = 0; j < loopTime; j++) { String str = i.toString(); } system.out.println (" integer.toString () : "+ (system.currentTimemillis () -startTime) + "ms"); startTime = System.currentTimeMillis(); for (int j = 0; j < loopTime; j++) { String str = i + ""; } system.out.println (" I + \"\" : "+ (system.currentTimemillis () -startTime) + "ms"); }Copy the code

The running results are as follows:

String.valueof () : 11ms Integer.toSTRING () : 5ms I + “” : 25ms

Therefore, the toString() method will be preferred when converting a primitive data type toString. As for why, it’s simple:

  • The string.valueof () method calls integer.tostring () underneath, but shorts the judgment before calling it

  • The integer.toString () method is called instead

  • I + “” is implemented using StringBuilder, which uses append method to concatenate the string, and toString() method to retrieve the string

Compared with the three, it is obvious that 2 is the fastest, 1 is the second, and 3 is the slowest

34. Use the most efficient way to traverse the Map

There are many ways to traverse a Map. Generally, we need to traverse keys and values in a Map. The most efficient way is recommended as follows:

public static void main(String[] args) { HashMap<String, String> hm = new HashMap<String, String>(); hm.put("111", "222"); Set<Map.Entry<String, String>> entrySet = hm.entrySet(); Iterator<Map.Entry<String, String>> iter = entrySet.iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); System.out.println(entry.getKey() + "\t" + entry.getValue()); }}Copy the code

If you just want to iterate over the Map’s keys, use Set keySet = hm.keyset (); Would be more appropriate.

35. It is recommended to separate close() for resources

Let’s say I have this code:

try {	
    XXX.close();	
    YYY.close();	
} catch (Exception e) {	
    ...	
}
Copy the code

You are advised to change the value to:

try {	
    XXX.close();	
} catch (Exception e) {	
    ...	
} 	
	
try {	
    YYY.close();	
} catch (Exception e) {	
    ...	
}
Copy the code

It’s a hassle, but it avoids resource leaks. Yyy. close() will not be executed, and YYY will not be recycled. It has been used for a long time. This code may cause resource handle leakage. XXX and YYY will be closed in any case

Remove ThreadLocal before or after using it

Almost all current projects use thread pooling technology, which is great because you can dynamically configure the number of threads and reuse threads.

However, if you use ThreadLocal in your project, be sure to remove it before or after using it. This is because the thread pool technique mentioned above does a thread reuse, which means that while code is running, a thread that has been used is not destroyed but is waiting for another use. We have a look at the Thread class, holding a ThreadLocal. ThreadLocalMap references:

/* ThreadLocal values pertaining to this thread. This map is maintained	
 * by the ThreadLocal class. */	
ThreadLocal.ThreadLocalMap threadLocals = null;
Copy the code

Article on the Thread does not destroy means the Thread set ThreadLocal. Data in a ThreadLocalMap still exists, then the next a Thread to reuse the Thread, is likely to get to is a Thread on the set of data rather than the content they want.

This is a very subtle problem, and it is very difficult to find errors due to this cause without experience or solid foundation, so pay attention to this when writing code, which will save you a lot of work later on.

Remember to replace the devil number with a constant definition

The presence of devil numbers greatly reduces code readability, and string constants can be defined using constants as the case may be

38. Initial assignment of long or long with a capital L instead of a lowercase L, since the letter L can easily be confused with the number 1, is a detail worth noting

39. All overridden methods must retain the @override annotation

There are three reasons to do this:

  • It is clear that this method is inherited from the parent class

  • The getObject() and get0bject() methods, whose fourth letter is “O” and whose fourth child is “0”, add the @override annotation to immediately determine whether the Override succeeded

  • Change a method signature in an abstract class, and the implementation class immediately reports a compilation error

40. We recommend using the new Objects utility class in JDK7 to compare equals(b) and null pointer exceptions

41. Instead of using “+” for string concatenation in the loop, use StringBuilder to append the string

To explain why I don’t use “+” for string concatenation, suppose I had a method:

public String appendStr(String oriStr, String... appendStrs) {	
    if (appendStrs == null || appendStrs.length == 0) {	
        return oriStr;	
    }	
	
    for (String appendStr : appendStrs) {	
        oriStr += appendStr;	
    }	
	
    return oriStr;	
}
Copy the code

Decompile this code into the.class file using Javap -C and intercept the key parts: This means that every time the virtual machine encounters the “+” operator to concatenate strings, it will create a New StringBuilder, call append, and then toString() to convert the string to an oriStr object. How many StringBuilder() will be new, which is a waste of memory.

Do not catch run-time exception classes that inherit from RuntimeException defined in the Java class library

Exception handling is inefficient and RuntimeException classes are RuntimeException classes, most of which can be completely circumvented by programmers, such as:

  • ArithmeticException can be circumvented by determining whether the divisor is empty

  • NullPointerException can be circumvented by determining whether an object is empty

  • IndexOutOfBoundsException can be avoid by judging the array/string length

  • ClassCastException can be circumvented using the instanceof keyword

  • ConcurrentModificationException can use iterator to evade

43. Avoid Random instances being used by multiple threads

While sharing this instance is thread-safe, performance degrades due to competing for the same seed. After JDK7, ThreadLocalRandom can be used to fetch random numbers.

To explain why competing for the same seed can cause performance degradation, for example, look at the nextInt() method implementation of the Random class:

public int nextInt() {	
    return next(32);	
}
Copy the code

Next (int bits) is called, which is a protected method:

protected int next(int bits) { long oldseed, nextseed; AtomicLong seed = this.seed; do { oldseed = seed.get(); nextseed = (oldseed * multiplier + addend) & mask; } while (! seed.compareAndSet(oldseed, nextseed)); return (int)(nextseed >>> (48 - bits)); }Copy the code

The seed here is a global variable:

/**	
 * The internal state associated with this pseudorandom number generator.	
 * (The specs for the methods in this class describe the ongoing	
 * computation of this value.)	
 */	
private final AtomicLong seed;
Copy the code

When multiple threads simultaneously acquire random numbers, they will compete for the same seed, resulting in a decrease in efficiency.

Static, singleton, and factory classes make their constructors private

This is because static classes, singleton classes, factory classes, etc. do not need to be externally new in the first place. Making the constructor private ensures that these classes do not generate instance objects.