11 Practical tips for Java performance tuning __java

Source: Internet
Author: User
Tags stringbuffer

Most developers believe that performance optimization is a more complex issue and requires a lot of experience and knowledge. Yes, it is not wrong. Admittedly, it's not easy to optimize your application for the best performance, but that doesn't mean you can't do anything without getting the experience and knowledge. Here are a few easy to follow suggestions and best practices that can help you create a good performance application.

Most of these recommendations are java-based, but not necessarily, and there are some that can be applied to all applications and programming languages. Before we share the Java-based performance tuning techniques, let's talk about these general performance tuning techniques first. 1. Do not optimize before necessary

This is probably one of the most important performance tuning techniques. You should follow common best practices and try to implement your use cases effectively. This does not mean replacing any of the standard libraries or building complex optimizations before proving it is necessary.

In most cases, premature optimization takes up a lot of time, making the code difficult to read and maintain. To make matters worse, these optimizations usually don't do any good because you spend a lot of time optimizing non-critical parts of your application.

So, how do you prove you need to optimize something?

First, you need to determine the speed of your application's code, for example, to specify a maximum response time for all API calls, or to specify the number of records to import in a specific time range. When you're done, you can measure which parts of your application are slow and need improvement. When you do this, keep looking at the second tuning technique. 2. Use the analyzer to find the real bottleneck

When you follow the first piece of advice and make sure that some parts of your application do need improvement, ask yourself where to start.

You can solve this problem in two ways: You can take a look at your code, starting with something that looks suspicious or that you think might be problematic. Or use a parser to get detailed information about the behavior and performance of each part of the code.

As for why should always follow the second method.

The answer should be obvious, the parser-based approach gives you a better understanding of the code's performance implications and allows you to focus on the most critical parts. If you've ever used a parser, you'll be amazed at what parts of your code are causing performance problems. However, most of the time, your first guess will lead you in the wrong direction. 3. Create a performance test suite for the entire application

This is another general technique that helps you avoid many unexpected problems that usually occur after performance improvements are deployed to the production environment. You should often define a performance test suite that tests the entire application and run it before and after you complete the performance improvement.

These additional test runs will help you identify the functional and performance implications of the changes and ensure that you do not post an update that does more harm than good. This is especially important if your task runs in several different parts of your application, such as a database or cache. 4. First, solve the biggest bottleneck problem

After you create a test suite and analyze your application using the parser, you have a list of issues that you need to improve performance, which is fine, but it still doesn't answer the question where you should start. You can start with something that can be done quickly, or from the most important ones.

Of course, the former is tempting, because it will soon be the result. Sometimes, it may be necessary to convince other team members or your management that performance analysis is worthwhile.

But in general, I recommend starting with the most important performance issues. This will provide you with the greatest performance improvements, and you may need to fix just a few of these problems to address your performance requirements.

After understanding the general performance tuning techniques, let's take a closer look at some Java-specific tuning techniques. 5. Use StringBuilder to connect strings programmatically

There are many different options for connection strings in Java. For example, you can use a simple + or + =, old StringBuffer or StringBuilder.

So, which method should you choose?

The answer depends on the code of the connection string. If you add new content to a string programmatically, for example, in a for loop, you should use StringBuilder. It is easier to use and provide better performance than StringBuffer. But keep in mind that unlike StringBuffer, StringBuilder is not thread-safe and may not be appropriate for all use cases.

You just need to instantiate a new StringBuilder and call the Append method to add a new part to the string. When you have added all the parts, you can call the ToString () method to retrieve the connection string.

The following code fragment shows a simple example. In each iteration, the loop converts I to a string and adds it to StringBuilder SB's space, so that in the end, this code is written to "This is test0123456789" to the log file.

1 2 3 4 5 6 StringBuilder sb = new StringBuilder ("This is a Test");       for (int i= 0; i< i++) {sb.append (i);  Sb.append (""); } log.info (Sb.tostring ());

As you can see in the code snippet, you provide the first element of the string for the constructor method. This creates a new StringBuilder that contains the supplied string and the capacity of 16 extra characters. When you add more characters to the StringBuilder, the JVM will dynamically change the size of the StringBuilder.

If you already know how many characters your string contains, then you can provide this number to a different constructor method to instantiate a StringBuilder with the defined capacity. This further increases its efficiency because it does not need to dynamically expand its capacity. 6. Use the + connection string in the Declaration

When you implement the first application in Java, someone may tell you that you should not use the + to connect strings. This is true if you are connecting strings in application logic. Strings are immutable, and the result of each string connection is stored in a new string object. This requires additional memory and lowers the speed of the application, especially when connecting multiple strings in a loop.

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

But if you're just splitting a string into multiple lines to improve the readability of your code, that's not the case.

1 2 3 Query q = Em.createquery ("Select a.ID, A.firstname, a.lastname" + "from Author a" + "WHERE a.id =: id");

In these cases, you should use a simple + to connect your string. The Java compiler optimizes it and performs a connection at compile time. Therefore, at run time, the code uses only 1 characters and does not require a connection. 7. Use basic data types whenever possible

Another way to avoid overhead is to use the original data type rather than the wrapper class for improving application performance. Therefore, it is best to use int instead of integer, or double instead of double. This will allow the JVM to store the value on the stack to reduce memory consumption and handle it more efficiently. 8. Avoid BigInteger and BigDecimal as far as possible

Since we've discussed the data types, let's look at BigInteger and BigDecimal. Especially the latter, because of its high precision and popular. But there's a price to it.
BigInteger and BigDecimal require more memory than simple long or double, and greatly reduce all computational speed. So if you need extra precision, or if your number exceeds a long range, it's best to think twice before you do it. This may be the only place you need to change your performance problems, especially if you are implementing a mathematical algorithm. 9. Check the current log level first

This suggestion is obvious, but unfortunately, you'll find that a lot of code ignores it. Before you create a debug message, you should check the current log level first.

Here are two examples to illustrate that you should not do this.

1 2 3 4 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 you need to create a log message without knowing whether the log frame uses log messages. Before you create a debug message, it is a good idea to check the current log level first.

1 2
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.