Android StringBuilder vs String Concatenation

孤人 提交于 2019-12-03 02:08:21

The compiler does exactly what you suggest is implied. You can print the bytecodes of the generated .class file (using javap -c) and see the calls to construct and use a StringBuilder.

However, it's generally worth doing it manually when the string concatenations are spread over several lines of code. The compiler usually allocates a separate StringBuilder for every String-valued expression involving +.

Ted Hopp's answer is good, but it took reading it a few times to understand. Here is a rephrased answer that is hopefully more clear.

String concatenation (ie, using +, as in String myString = "Hello " + "World";) uses a StringBuilder in the background along with other allocations. Thus, for anything other than a simple one-time concatenation, it would be better to use a StringBuilder yourself.

For example,

StringBuilder myString = new StringBuilder();
myString.append("Hello ");
myString.append("to ");
myString.append("everyone ");
myString.append("in ");
myString.append("the ");
myString.append("world!");

is better than

String myString = "Hello " + "to " + "everyone " + "in " + "the " + "world!";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!