还是在字符串附加vs concat vs + [英] Yet again on string append vs concat vs +

查看:134
本文介绍了还是在字符串附加vs concat vs +的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是我分裂的头发,但我想知道在下面的情况:

  String newString = a + b + C; // case 1 


String newString = a.concat(b).concat(c); // case 2

StringBuilder newString = new StringBuilder(); // case 3
newString.append(a);
newString.append(b);
newString.append(c);

最好使用哪一种?



最好的意思是任何方式



阅读这些,其他帖子说,情况3不是最佳的性能明智,其他人的情况1将最终在情况3等。



更具体地说。



例如,设置全部,如果你必须维护他的代码,哪种风格更适合从另一个程序员看到它?



或者你会认为编程效率更高吗?

或者你会认为更快等。



我不知道如何表达这一点。



情况3可以更快,但绝大多数程序员喜欢案例1,因为它是最可读的也被接受,如果它在某种程度上详细阐述

解决方案

情况1简洁,表达的意图清楚,并等同于情况3.



情况2效率较低,也较少可读性。



案例3几乎与案例1一样高效,但时间更长,可读性更差。



只有当你必须在循环中连接时才更好。否则,编译器将case 1编译为case 3(除了它构造StringBuilder与 new StringBuilder(a)),这使它甚至比你的情况3) / p>

May be I am splitting hair, but I was wondering in the following case:

String newString = a + b + c;  //case 1


String newString = a.concat(b).concat(c);   //case 2

StringBuilder newString = new StringBuilder(); //case 3
newString.append(a);
newString.append(b);    
newString.append(c);

Which is the best to use?

Best I mean in any way.

Reading about these, other posts say that the case 3 is not that optimal performance wise, others that case 1 will end up in case 3 etc.

To be more specific.

E.g., setting all aside, which style is more suitable to see it from another programmer if you had to maintain his code?

Or which would you consider as more programming efficient?
Or you would think is faster etc.

I don't know how else to express this.

An answer like e.g. case 3 can be faster but the vast majority of programmers prefer case 1 because it is most readable is also accepted if it is somehow well elaborated

解决方案

Case 1 is concise, expresses the intent clearly, and is equivalent to case 3.

Case 2 is less efficient, and also less readable.

Case 3 is nearly as efficient as case 1, but longer, and less readable.

Using case 3 is only better to use when you have to concatenate in a loop. Otherwise, the compiler compiles case 1 to case 3 (except it constructs the StringBuilder with new StringBuilder(a)), which makes it even more efficient than your case 3).

这篇关于还是在字符串附加vs concat vs +的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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