Detailed explanation of string splicing examples in jdk8

preface

Among Java developers, string splicing takes up a lot of resources, which is often a hot topic

Let's discuss in depth why it takes up high resources.

In Java, a string object is immutable, which means that once it is created, you can't change it. So when we splice strings, we create a new string, and the old one is marked by the garbage collector.

If we process millions of strings, then we will generate millions of additional strings to be processed by the garbage collector.

In most tutorials, you may see that splicing strings with the + sign will generate multiple strings, resulting in poor performance. It is recommended to use StringBuffer / StringBuilder to splice.

But is that really the case?

The following experiments are done in jdk8:

Decompile through javap - C to get:

You can see that the java compiler optimizes the generated bytecode, automatically creates a StringBuilder and performs the append operation.

Since the substring to build the final string is already known at compile time, the java compiler will perform the above optimization in this case. This optimization is called a static string concatenation optimization and has been enabled since jdk5.

Does that mean that after jdk5, we no longer need to manually generate StringBuilder, and the same performance can be achieved through the + sign?

Let's try the following dynamic splicing string:

A dynamically spliced string refers to a substring of the final string that is known only at run time. For example, add a string to the loop:

Also decompile:

You can see that new StringBuilder was created at 14, but goto reached 5 at 37. During the cycle, it did not achieve optimization and continued to generate new StringBuilder.

So the above code is similar:

You can see that new stringbuilders are constantly generated, and through toString, the original StringBuilder will no longer be referenced as garbage, which also increases the cost of GC.

Therefore, in actual use, when you can't distinguish between static splicing and dynamic splicing, you'd better use StringBuilder.

Reference:

http://www.pellegrino.link/2015/08/22/string-concatenation-with-java-8.html

summary

The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>