Java Performance Tuning Tips

1. Prior to optimize the system do not need to know

This is probably one of the most important performance tuning tips. You should follow common best practices and try to implement use cases efficiently. However, this does not mean that until you prove necessary, you should replace any standard library or build complex optimization.

In most cases, premature optimization will not only take up a lot of time and make the code difficult to read and maintain. Worse, these optimization usually does not bring any good, because you spend a lot of time to optimize a non-critical part of the application.

So how do you prove that you need to optimize something here?

First, you need to define the speed of application code much more quickly, for example, specifies the maximum response time for all the API calls, or specify the number of records within a certain time range to be imported. After completing these, you can measure what parts of the application is too slow need to improve. Then, then look at the second skill.

2. Use a profiler to find the real bottleneck

After you follow the first proposal and identified certain parts of the application need to be improved, so where to start?

You can use two methods to solve the problem:

  • Check your code and start from the looks suspicious or you think it might be problematic part.
  • Or using the analyzer and obtain more information about the behavior and performance of each portion of the code.

I hope that does not need to explain the reason why you should always follow the second method.

Clearly, based on the method of analyzer allows you to better understand the performance impact of the code, and you can focus on the most critical part. If you have used the analyzer, then you must remember how much you surprised at what you find which parts of the code creates performance issues. To be honest, my first guess more than once led me in the wrong direction.

3. Create a performance test suite for the entire application

This is another general tips that can help you avoid many unexpected problems after deploying to improve the performance of production often occur. You should always define a test for the entire application performance test suite and run it before and after performance improvements.

These additional test runs will help you identify the functionality and performance of the side effects of the changes and to ensure that does not cause more harm than good update. If you work in a number of different components are used in parts of the application, such as a database or cache, then this is especially important.

4. First, the biggest bottleneck process

After creating a test suite and analytic applications using the analyzer, you can list a series of problems need to be addressed in order to improve performance. That's fine, but it still does not answer the question you should be where to start. You can focus on quick-impact programs, or start from the most important issue.

Quick start program might be very attractive because you can quickly show the first results. But sometimes, you may need to convince other team members or management believes that performance analysis is worth it - because do not see the effect.

But in general, I recommend starting with the most important performance issues. This will provide you with the greatest performance improvement, and may no longer need to solve some of these problems in order to meet performance requirements.

Common performance tuning techniques to this end. Let's take a closer look at some of the specific techniques in Java.

5. String StringBuilder connected to programmatically

There are many different options to connect in Java String. For example, you can use simple + or + =, and StringBuffer or StringBuilder.

So which method should you choose?

The answer depends on the connection String code. If you are adding new content to a String programming mode, for example in a for loop, then you should use StringBuilder. It is easy to use and offers better performance than StringBuffer. But remember, compared with StringBuffer, StringBuilder is not thread safe and may not be suitable for all use cases.

You only need to instantiate and call a new StringBuilder append method to add a new section to the String. After you add all the parts, you can call toString () method to retrieve String connection.

The following code fragment shows a simple example. During each iteration, the loop i is converted to a String, and added to it with a space in StringBuilder sb. Therefore, finally, the code is written to the log file "This is a test0 1 2 3 4 5 6 7 8 9".

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 above code fragment, you can provide the first element of the String to the constructor. This will create a new StringBuilder, new StringBuilder String containing capacity and 16 extra characters provided. When you add more characters to the StringBuilder, JVM will dynamically increase the size of a StringBuilder.

If you already know your String will contain the number of characters, it can provide the numbers to a different constructor to instantiate StringBuilder has a defined capacity. This further improves the efficiency, because it does not require dynamic expansion of its capacity.

6. Use a connection statement + String

When you use Java to achieve your first application, you may have been told you should not have to connect with String +. If you are the connection string in the application logic, that's right. Strings are immutable, the results of each string is connected are stored in a new String object. This requires additional memory, it will slow down your application, especially if you connect multiple strings of words within a loop.

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

However, if you just string into multiple lines to improve readability of the code, that 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 perform this optimization and connection at compile time. So, at run time, your code will only use a String, need not be connected.

7. Use as primitives

Avoid any overhead and another program performance applications easy and fast way to improve is to use a basic type rather than its packaging. Therefore, the best use int instead of Integer, instead of using the double Double. This allows the JVM value stored in the stack instead of the heap to reduce memory consumption , and a more effective treatment.

8. try to avoid BigInteger and BigDecimal

Since we are talking about data types, then we take a quick look BigInteger and BigDecimal it. Especially the latter because of its accuracy and welcomed by everyone. But this comes at a price.

BigInteger and BigDecimal requires more memory than simple long or double, and can significantly slow down all calculations. So, if you need extra precision, or the number will exceed the long range, it is best to think twice. This may be the only way to solve the performance issues you need to change, especially when implementing a mathematical algorithm.

9. First, check the current log level

This proposal should be obvious, but unfortunately, many programmers when writing code will mostly ignore it. Before you create debug messages, and always should first check the current log level. Otherwise, you might create a log will be ignored after the message string.

There are two negative examples.

// 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 above, you will perform all the necessary steps to create a log message, without knowing whether logging framework will use the log messages premise. So before creating debug messages, it is best to check the current log level.

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

10. Use Apache Commons StringUtils.Replace instead String.replace

In general, String.replace method works fine, high efficiency, especially in the case of the use of Java 9. However, if your application requires a lot of replacement operation, and no update to the latest version of Java, then we still need to find a faster and more effective alternatives.

There is an alternative answer Apache Commons Lang's StringUtils.replace method. As Lukas Eder in his recent blog post described, StringUtils.replace method is far better than Java String.replace method 8.

And it only needs minor modifications. That added Apache Commons Lang project Maven pom.xml dependencies into the application, all calls and replace String.replace method for StringUtils.replace method.

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

11. The cache expensive resources, such as database connections

The cache is used to avoid repeatedly performing an expensive piece of code or popular solutions. The general idea is simple: re-use these resources to be cheaper than repeatedly create new resources.

A typical example is a database connection pool cache. Create a new connection takes time, if you reuse an existing connection, you can avoid this situation.

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 that creating a new Integer is not too expensive, but because it is often used, so that the cache of the most commonly used values ​​can also provide performance advantages.

However, when you consider caching, remember cache implementation will produce overhead. You need to spend extra memory to store reusable resources, so you may need to manage the cache so that resources can be accessed, and delete obsolete resources.

So, before you start any cache resources, ensure the implementation of the cache is worth it, that you must use them enough and more.

to sum up

As you can see, sometimes it does not require much work can improve the performance of your application. Much of the advice in this article requires only a little effort you can apply them to your code.

However, the most important thing that has nothing to do with what programming language skills:

  • Do not optimize before you need to know
  • Use a profiler to find the real bottleneck
  • First, the biggest bottleneck process

Guess you like

Origin www.cnblogs.com/sunshinekevin/p/11525033.html