11 Concise Java Performance Tuning tips

Source: Internet
Author: User

Want to keep your project running at high performance? Here are some tips you can take to eliminate cache bottlenecks, as well as some other performance tuning recommendations.

Most developers think that performance optimization is a complex topic that requires a lot of work experience and relevant knowledge theory. Well, it's not entirely wrong. Optimizing an application for performance optimization may not be an easy task, but it doesn't mean that you don't have the knowledge to do anything. Here are some easy-to-follow recommendations and best practices to help you create a well-performing application.

Most of these recommendations are for the Java language. But there are also some language-independent, you can apply to any application and program. Before we learn about specific Java programming performance tuning, let's explore some common tricks.

    1. Don't be so quick to optimize before you need to be clear.

This is probably one of the most important performance optimization techniques. You should follow common best practices and apply them efficiently in a case. But this does not mean that you should replace any standard library or build complex optimizations before proving necessary.

In most cases, premature optimization takes a lot of time and makes the code difficult to understand and read. To make matters worse, these optimizations do not usually bring any benefit because you spend a lot of time optimizing the non-critical parts of your application.

So, how do we prove that things need to be optimized?

First, you need to define how fast your code is. For example, specify the maximum response time for all API calls, or specify the number of records to import within a specific time range. After you've done this, you need to determine which parts of your app are too slow to improve. When you're done, you can take a look at the second tip.

    1. Using analyzers to find real bottlenecks

Where do you start by completing the first part of the optimization recommendations to identify the parts of your application that need to be promoted?

You can solve this problem in two ways:

1) Look at your code and start with something that looks suspicious or that you think might cause problems

2) or use the parser to get detailed information about the behavior (execution process) and performance of each part of the code.

Hopefully I don't need to explain why you should always follow the second approach/method.

Obviously, a parser-based approach can give you a better understanding of the performance impact of your code and allow you to focus on the more critical Parts (code). Even if you've ever used a profiler, you'll remember how surprised you were to find out which parts of the code produced performance problems. My first guess led me to go the wrong way more than once.

    1. Create a performance test suite for the entire application

This is another common technique that can help you avoid many of the unexpected problems that often occur after you deploy performance improvements to your product. You should always define a performance test suite to test the entire application and run it before and after performance improvements.

These additional test runs will help you to identify the functional and performance side effects of your changes and ensure that there are no more harmful updates than the benefits. This is especially important if you are dealing with components that are used by several different parts of the application, such as databases or caches.

    1. Priority attention to maximum bottlenecks

After you have created a test suite and analyzed your application using the parser, you can list a series of issues that need to be addressed to improve performance. That's fine, but that doesn't answer the question of where you need to start. You can focus on crash scenarios, or start with the most important questions.

A crash scenario might be attractive at first because you can quickly show the first result. But sometimes it may be necessary to convince other team members or management that performance analysis is worthwhile.

In general, I recommend starting with the top level and starting with the most important performance issues first. This will provide you with the greatest performance improvements, and you may need to address only a small subset of these issues to meet your performance requirements.

This is the end of common general tuning techniques. Now let's take a closer look at some Java-specific tricks.

    1. To concatenate strings programmatically using StringBuilder

There are a number of different options in Java to concatenate strings. For example, you can use a simple + or + =, as well as an old StringBuffer or StringBuilder.

So, which method should you choose?

The answer depends on the code of the connection string. If you are programmatically adding new content to a string, such as in A For loop, you should use StringBuilder. It is easy to use and offers better performance than StringBuffer. Keep in mind, however, that StringBuilder is not thread-safe compared to stringbuffer, and may not work in all cases.

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

The following code snippet shows a simple example. During each iteration, the loop converts I to a String and adds it to the StringBuilder SB with a space. So, finally, this code writes in the log file "This is a Test0 1 2 3 4 5 6 7 8 9".

StringBuilder SB =newstringbuilder ("This is a Test"), for (inti=0; i<10; i++) {

Sb.append (i);

Sb.append ("");

}

Log.info (Sb.tostring ());

As you can see in our code snippet for the Java technology stack, we could provide the first element of a string to the constructor. This creates a StringBuilder that contains the string you provide and the capacity of 16 additional characters. When you add more characters to StringBuilder, your JVM will dynamically increase the size of the StringBuilder.

If you already know how many characters a string will contain, you can give that number to a different construction method to instantiate a StringBuilder with the specified capacity. This further increases efficiency because it does not need to dynamically scale its capacity.

    1. Use + to concatenate a string in a statement

When you use Java to implement your first application, someone may have told you not to use + to concatenate strings. This is true if you are connecting strings within the application logic. The string is immutable, and the connection result for each string is stored in a new string object. This requires additional storage space and may make your application run slowly, especially if you are connecting multiple strings within a loop.

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

But if you just split the string into multiple lines to improve the readability of the code, that doesn't apply.

Query q = em.createquery ("Selecta.id, A.firstname, A.lastname"

    • "Fromauthor a"

    • "Wherea.id =: id");

In these scenarios, you should use a simple + to concatenate strings. Your Java compiler optimizes it and completes the connection at compile time. Therefore, at run time, your code will use only one string, and no connection operation is required.

    1. Use basic types whenever possible

Another easy and quick way to avoid any overhead and improve application performance is to use the base type instead of its wrapper class. Therefore, it is better to use int instead of Integer, double instead of double. This will allow your JVM to store the value on the stack instead of the heap to reduce memory consumption and handle it more efficiently.

    1. Try to avoid large integers and decimals

Since we are already discussing data types, we should also quickly browse large integers and decimals. In particular, the latter is popular for its accuracy. But that comes at a price.

Large integers and decimals require more memory than a simple long or double type, and will significantly slow down all operations. So, if you need extra precision, or if your numbers go beyond a longer range, it's best to think twice. This may be the only way you need to change and resolve performance issues, especially when implementing a mathematical algorithm.

    1. Prioritize checking the current log level

This suggestion should be obvious, but unfortunately, many people ignore it when they write code. Before you create a debug message, you should always check the current log level first. Otherwise, you might create a string that attaches your log messages, and the string will be ignored after that.

Here are two negative examples of what you should not do.

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 of these examples, you will perform all the necessary steps to create a log message without knowing whether the log framework will use log messages. Therefore, it is a good idea to check the current log level before creating a debug message.

Do Thisif (log.isdebugenabled ()) {

Log.debug ("user[" + UserName + "]called method X with[" + i + "]");

}

    1. Use Apache Commons stringutils.replace instead of String.Replace

In general, the String.Replace method works and is highly efficient, especially if you use Java 9. However, if your application requires a lot of replacement operations and is not updated to the latest Java version, it is still necessary to check for faster and more efficient alternatives.

One candidate scheme is Apache Commons Lang's Stringutils.replace method. As Lukas Eder in one of his recent blog posts, it outperforms Java 8 's string.replace approach.

And it just needs a little change. You only need to add the Maven dependency of the Apache Commons Lang project to the pom.xml of your application and replace all String.replacemethod calls with the Stringutils.replace method.

Replace this

Test.replace ("Test", "simpletest");

With this

Stringutils.replace (Test, "test", "simpletest");

11. Expensive cache resources, such as database connections

Caching is a popular solution to avoid repetitive execution of expensive or frequently used code snippets. The general idea is simple: reusing these resources is more cost-effective than creating a new resource.

A typical example is the database connection in the cache pool. The creation of a new connection takes time, and if you reuse an existing connection, you can avoid this situation.

You can also find other examples in the Java language source code. For example, the ValueOf method in the Integer class caches a value between 128 and 127. You might say that creating a new Integer is not too expensive, but because it is often used, the most commonly used value for caching can also be the advantage of XXX.

However, when you consider using caching, remember that caching implementations also incur overhead. You need to spend extra memory to store reusable resources, so you might need to manage your cache to make resources accessible and remove outdated resources.

Therefore, before you start caching any resources, make sure that they are used frequently to exceed the overhead (cost) of the cache implementation.

Summarize

As you can see, sometimes it doesn't take too much work to improve the performance of your application. Most of the recommendations in this article require a little effort to apply them to your code.

But still, the most important ones are those that have nothing to do with programming languages:

Do not optimize until you know the need for it

Use the profiler to find a real bottleneck

Prioritize the biggest bottlenecks

1, with 1-5 of working experience, in the face of the current popular technology do not know where to start, the need to break through the technical bottleneck can add group.

2, in the company for a long time, have a very comfortable, but job-hopping interview wall. Need to study in a short period of time, job-hopping to get a high salary can add group.

3, if there is no work experience, but the foundation is very solid, Java work mechanism, common design ideas, commonly used Java Development Framework Master Skilled, can add group.

4, feel that they are very cow B, the general needs can be done. However, the knowledge points are not systematic, it is difficult to continue to breakthrough in the technical field can add group.

5. Group No. 744677563

6. Ali Java senior Daniel Live to explain the knowledge points, share knowledge, knowledge points are the teachers of many years of work experience of the carding and summary, with everyone comprehensive, scientific to establish their own technical system and technical knowledge!

11 Concise Java Performance Tuning tips

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.