Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

performance - What happens when Java Compiler sees many String concatenations in one line?

Suppose I have an expression in Java such as:

String s = "abc" + methodReturningAString() + "ghi" + 
                anotherMethodReturningAString() + "omn" + "blablabla";

What's the behaviour of the Java's default JDK compiler? Does it just makes the five concatenations or there is a smart performance trick done?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It generates the equivalent of:

String s = new StringBuilder("abc")
           .append(methodReturningAString())
           .append("ghi")
           .append(anotherMethodReturningAString())
           .append("omn")
           .append("blablabla")
           .toString();

It is smart enough to pre-concatenate static strings (i.e. the "omn" + "blablabla"). You could call the use of StringBuilder a "performance trick" if you want. It is definitely better for performance than doing five concatenations resulting in four unnecessary temporary strings. Also, use of StringBuilder was a performance improvement in (I think) Java 5; prior to that, StringBuffer was used.

Edit: as pointed out in the comments, static strings are only pre-concatenated if they are at the beginning of the concatenation. Doing otherwise would break order-of-operations (although in this case I think Sun could justify it). So given this:

String s = "abc" + "def" + foo() + "uvw" + "xyz";

it would be compiled like this:

String s = new StringBuilder("abcdef")
           .append(foo())
           .append("uvw")
           .append("xyz")
           .toString();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...