Java String concatenation and Performance

Source: Internet
Author: User

Overview:This article mainly studies the performance of String concatenation in Java. The test code in the original article is not functionally equivalent, so the test of Concat is of little significance. However, the original author gave a new Concat result in the comment bar. If you are interested, you are advised to modify the code for testing.

Source: http://www.venishjoe.net/2009/11/java-string-concatenation-and.html

The simplest way to splice two strings in Java is to use the operator "+. If you use "+" to connect strings with a fixed length, the possibility will be slightly affected, but if you are using "+" in a loop, the performance will be exponentially reduced. Suppose there is a string, we will perform a lot of loop concatenation operations on this string, using "+" will get the lowest performance. But how poor is the performance? What if we also put stringbuffer, stringbuilder or string. Concat () into performance testing? This article will give an answer to these questions!

We will use per4j to calculate the performance, because this tool can give us a complete set of performance indicators, such as the minimum, maximum time consumed, and standard deviation in the statistical period. In the test code, in order to get an accurate standard deviation value, we will perform 20 "*" 50,000 tests. The following is the concatenation string method we will use:

  • Concatenation Operator (+)
  • String concat method-concat (String str)
  • StringBuffer append method-append (String str)
  • StringBuilder append method-append (String str)

Finally, we will look at the bytecode to study how these methods are executed. Now, let's start to create the class that comes with me. Note that to calculate the performance of each loop, each test code segment in the Code must be encapsulated using the per4j library. First, we define the number of iterations.

private static final int OUTER_ITERATION=20;private static final int INNER_ITERATION=50000;

Next, we will use the above four methods to implement our test code.

String addTestStr = "";String concatTestStr = "";StringBuffer concatTestSb = null;StringBuilder concatTestSbu = null;for (int outerIndex=0;outerIndex<=OUTER_ITERATION;outerIndex++) {    StopWatch stopWatch = new LoggingStopWatch("StringAddConcat");    addTestStr = "";    for (int innerIndex=0;innerIndex<=INNER_ITERATION;innerIndex++) addTestStr += "*";    stopWatch.stop();}        for (int outerIndex=0;outerIndex<=OUTER_ITERATION;outerIndex++) {    StopWatch stopWatch = new LoggingStopWatch("StringConcat");    concatTestStr = "";    for (int innerIndex=0;innerIndex<=INNER_ITERATION;innerIndex++) concatTestStr = concatTestStr.concat("*");    stopWatch.stop();}for (int outerIndex=0;outerIndex<=OUTER_ITERATION;outerIndex++) {    StopWatch stopWatch = new LoggingStopWatch("StringBufferConcat");    concatTestSb = new StringBuffer();    for (int innerIndex=0;innerIndex<=INNER_ITERATION;innerIndex++) concatTestSb.append("*");    stopWatch.stop();}for (int outerIndex=0;outerIndex<=OUTER_ITERATION;outerIndex++) {    StopWatch stopWatch = new LoggingStopWatch("StringBuilderConcat");    concatTestSbu = new StringBuilder();    for (int innerIndex=0;innerIndex<=INNER_ITERATION;innerIndex++) concatTestSbu.append("*");    stopWatch.stop();}

Next, run the program to generate performance indicators. My runtime environment is a 64-bit ipvwn7 operating system, 32-bit JVM (7-ea) with 4 GB memory, dual-core quad 2.00ghz CPU machine.

After 20 iterations, we get the following data:

The results were perfect as we thought. The only interesting thing is why string. concat is also very good. We all know that string is a common class (the class won't be changed after initialization), so why does Concat have better performance. (Translator's note: In fact, there is a problem with the test code of the original author. The test code of the concat () method should be written as concatTestStr = concatTestStr. concat .) To answer this question, we should look at the bytecode decompiled by concat. The downloaded package in this article contains all the bytecode, but now let's take a look at the concat code snippet:

45: new #7; //class java/lang/StringBuilder48: dup49: invokespecial #8; //Method java/lang/StringBuilder."":()V52: aload_153: invokevirtual #9; //Method java/lang/StringBuilder.append:    (Ljava/lang/String;)Ljava/lang/StringBuilder;56: ldc #10; //String *58: invokevirtual #9; //Method java/lang/StringBuilder.append:    (Ljava/lang/String;)Ljava/lang/StringBuilder;61: invokevirtual #11; //Method java/lang/StringBuilder.toString:()    Ljava/lang/String;64: astore_1

This code is String. concat () bytecode, from this code, we can clearly see that the concat () method uses StringBuilder, concat () performance should be as good as StringBuilder, however, the StringBuilder is created and implemented. append (str ). append (str ). the toString () operation affects the performance of concate. Therefore, the time required for StringBuilder and String Cancate is 1.8 and 3.3.

Therefore, if we do not want to create a StringBuffer or StringBuilder instance during the simplest splicing, we should also use concat. However, for a large number of String concatenation operations, we should not use concat (Note:Because the function of the test code is not fully equivalent, the average processing time of the changed test code concat is 1650.9 milliseconds. This result is included in the original comment .), Because concat will reduce the performance of your program and consume your cpu. Therefore, we should try to use StringBuilder to achieve the highest performance without considering thread security and synchronization.

Source:Http://coolshell.cn /? P = 2235

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.