ajd*_*uke 7 java concat string-concatenation string-formatting
哪一个更适合串联连接
如果我想从一串字符串变量(如str1和str2)构建一个字符串,哪一个会更好一个?
String str="This the String1 " + str1 + " merged with Sting2 " + str2;
String str=String.format("This the String1 %s merged with Sting2 %s", str1 , str2);
我认为第二个会更好,因为第一个会受到很多字符串创建的影响.
如果我错了,请纠正我?并提供相同的反馈
第一个实际上不会创建任何额外的字符串.它将被编译成类似于:
String str = new StringBuilder("This the String1 ")
.append(str1)
.append(" merged with Sting2 ")
.append(str2)
.toString();
Run Code Online (Sandbox Code Playgroud)
鉴于第二种形式需要解析格式字符串,如果第一种形式实际上运行得更快,我不会感到惊讶.
但是,除非你有基准来证明这确实是一些运行速度太慢的代码,否则你不应该太担心效率.你应该更担心可读性.您觉得哪些代码更具可读性?