Java Performance Tuning 11 practical tips

1. Before necessary, to do optimization

This is probably one of the most important performance tuning techniques. You should follow common best practices and try to effectively implement your use case. But that does not mean proof before it is necessary, replace any standard library or build complex optimization.

In most cases, premature optimization takes a lot of time, making the code difficult to read and maintain. Worse, these optimization usually does not bring any good, because you spend a lot of time optimizing non-critical parts of the application.

So how do you prove that you need to optimize certain things?

First, you need to determine the speed of the application code, e.g., all API calls to a specified maximum response time, or a specified number of records into a specific time period. Once done, you can measure what parts of the application is too slow and needs to be improved. When doing so, please read the second tuning tips.

2. Use a profiler to find the real bottleneck

After you follow the first suggestion, and to identify certain parts of your application does need improvement, ask yourself where to start?

You can use two methods to solve this problem:

You can look at your code, starting from the looks suspicious or you think it might be problematic part.

Or using the analyzer, behavior and performance details of each portion of code acquisition.

As for why you should always follow the second method.

The answer should be obvious, based on the method of analyzer allows you to better understand the performance implications of code, and allows you to focus on the most critical part. If you've ever used an analyzer, you'll be amazed at what parts of the code causing performance problems. However, many times, your first guess will lead you to the wrong direction.

 

3. Create a performance test suite for the entire application

This is another general tips to help you avoid many unexpected problems, these problems usually occur after deployment into the production environment to improve performance. You should always test the whole application of the definition of performance test suite and run it before and after you complete performance improvements.

These additional test runs will help you identify changes affect the functionality and performance, and make sure you do not release updates a more harm than good. If your task to run on many different parts of the application such as a database or cache, which is especially important.

4. First solve the biggest bottleneck

After creating a test suite using the analyzer for analysis of the application, you will have a list of questions need to improve performance, that's fine, but it still does not answer the question you should be where to start. You can also start or begin from those who can quickly get from the most important issue.

Of course, the former is very attractive, because it will soon be the result. Sometimes, you may need to convince other team members or your management, performance analysis is worth it.

But in general, I would suggest first of all tackle the most important performance issues. This will provide you with the greatest performance improvements, and you may only need to fix some of these problems can be solved your performance requirements.

In the understanding of general performance tuning tips, let's take a closer look at some specific tuning tips on Java's.

5. StringBuilder string connected to programmatically

There are many different options for the connection string in Java. For example, a simple + or + =, or old StringBuffer StringBuilder.

So which method should you choose?

The answer depends on the connection string in the code. If you add new content to string programmatically, for example, in a for loop, you should use StringBuilder. It's easier to use than StringBuffer and provide better performance. But remember, different StringBuilder with StringBuffer, it is not thread-safe and may not be suitable for all use cases.

You only need to instantiate a new StringBuilder, and calls the append method to add a new section in the string. When you add up all the parts, you can call toString () method to retrieve the connection string.

The following code fragment shows a simple example. In each iteration, the cycle i is converted to a string, and add it to the space StringBuilder sb, so in the end, this code is written "this is test0123456789" to the log file.

StringBuilder sb=new StringBuilder(“This is a test”);
for(int i=0;i<10;i++){
sb.append(i);
sb.append(”“);
}
log.info(sb.toString());

As seen in the code segment, you can provide a first element of the string to the constructor method. This will create a new StringBuilder, which contains capacity and 16 extra character string provided. When you add more characters to the StringBuilder, JVM will dynamically change the size of a StringBuilder.

 

If you already know your string contains a number of characters, then you can provide this number to a different function method to instantiate a StringBuilder has a defined capacity. This further improves its efficiency, because it does not need to dynamically expand its capacity.

6. In the connection string declaration +

When you achieve the first application in Java, you may have been told you should not have to concatenate strings with +. If the connection string in the application logic that is correct. Strings are immutable, the result is stored in each string connected to a new string object. This requires additional memory, and reduce the speed of application, especially when connected to the plurality of strings in a loop.

In these cases, you should follow the tip 5 and use StringBuilder.

But if you're just a string into multiple lines to improve readability of the code, it is not the case.

Query q=em.createQuery(“SELECT a.id,a.firstName,a.lastName”
+“FROM Author a”
+“WHERE a.id=:id”);

In these cases, you should be a simple + to connect your string. Java compiler will optimize it at compile time and execute the connection. Accordingly, at run time, only one character code is used, you need not be connected.

7. Use as basic data types

Another way to avoid the cost, quick way to improve program performance of applications that use primitive data types rather than their packaging. So it is better to use int instead of Integer, or double instead of Double. This will allow the JVM will value stored in the stack to reduce memory consumption, and deal more effectively with it.

8. avoid BigInteger and BigDecimal

As we have discussed data types, we'll look at the BigInteger and BigDecimal. Especially the latter, due to its high popularity accuracy. But this comes at a price.

BigDecimal BigInteger and require more memory than the simple long or double, and greatly reduce the calculation speed of all. So, if you need extra precision, or your figure exceeds the scope of a long, better think twice. This is probably the only place you need to change to improve performance in question, especially when you are implementing a mathematical algorithm.

9. First, check the current log level

This advice is obvious, but unfortunately, you'll find a lot of code to ignore it. Before you create a debug message, you should check the current log level.

Here are two examples to show that you should not do it.

//don’t do this
log.debug(“User[”+userName+“]called method X with[”+i+“]”);
//or this
log.debug(String.format(“User[%s]called method X with[%d]”,userName,i));

In both cases, you will perform all the steps required to create a log message, not knowing whether to use the logging framework log messages. Before you create a debug message, it is best to check the current log level.

//do this
if(log.isDebugEnabled()){
log.debug(“User[”+userName+“]called method X with[”+i+“]”);
}

10. Instead of using the Apache Commons StringUtils.Replace String.replace

In general, String.replace method works well, and very efficient, especially if you are using a Java 9. However, if the application requires a lot of replacement operation, and you have not updated to the latest version of Java, check faster and more effective alternative is still meaningful.

 

It is a candidate Apache Commons Lang's StringUtils.replace (https://commons.apache.org/proper/commons-lang/) method. As Lukas Eder described in his recent blog post (https://blog.jooq.org/2017/10/11/benchmarking-jdk-string-replace-vs-apache-commons-stringutils-replace/) in as it greatly exceeded the Java String.replace method 8.

It only needs minor changes. You only need to Apache's Commons Lang project to add a Maven dependency to your application pom.xml, and replace all String.replace method StringUtils.replace method call.

//replace this
test.replace(“test”,“simple test”);
//with this
StringUtils.replace(test,“test”,“simple test”);

11. The cache expensive resources, such as database connection

Caching is a popular solution to avoid repeatedly performed expensive or frequently used code fragments. The general idea is simple: the use of these resources than repeat again and again to create a new resource is much cheaper.

A typical example is the cache database connection pool. Create a new connection takes time, if reusing an existing connection can be avoided.

You can also find other examples in the Java language itself. For example, valueOf method for caching Integer values ​​between -128 and 127. You might say, create a new integer is not too expensive, but it is often used, caching the most commonly used values ​​provide performance benefits.

But when you consider caching, remember, the cache implementation will produce overhead. You need to spend extra memory to store reusable resources, and therefore may need to manage your cache to enable resources to be accessed or delete obsolete resources.

So, before you start any cache resources, make sure that is often used.

Guess you like

Origin www.cnblogs.com/xuyiding/p/11621903.html
Recommended