当Java编译器在一行中看到许多String串联时会发生什么? [英] What happens when Java Compiler sees many String concatenations in one line?

查看:71
本文介绍了当Java编译器在一行中看到许多String串联时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个Java表达式,例如:

Suppose I have an expression in Java such as:

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

Java的默认JDK编译器的行为是什么?它只是进行了五个串联,还是完成了一个聪明的性能技巧?

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?

推荐答案

它生成的等效项:

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

预连接静态字符串(即"omn" + "blablabla")足够聪明.如果需要,可以将StringBuilder的使用称为性能技巧".对于性能而言,绝对比执行五个串联导致四个不必要的临时字符串更好.另外,使用StringBuilder可以提高Java 5的性能(我认为).在此之前,使用StringBuffer.

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.

编辑:如注释中所指出的,仅当静态字符串位于串联开始时才被预先串联.否则将破坏操作顺序(尽管在这种情况下,我认为Sun可以证明其合理性).因此,鉴于此:

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";

它会像这样编译:

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

这篇关于当Java编译器在一行中看到许多String串联时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆