假设字符串a和b:
a += b
a = a.concat(b)
Run Code Online (Sandbox Code Playgroud)
引擎盖下,它们是一样的吗?
这里以concat反编译为参考.我希望能够反编译+运算符以查看它的作用.
public String concat(String s) {
int i = s.length();
if (i == 0) {
return this;
}
else {
char ac[] = new char[count + i];
getChars(0, count, ac, 0);
s.getChars(0, i, ac, count);
return new String(0, count + i, ac);
}
}
Run Code Online (Sandbox Code Playgroud) 对于字符串连接,我们可以使用concat()或concat运算符(+).
我尝试了以下性能测试,发现concat()字符串连接速度更快,内存效率更高.
字符串连接比较100,000次:
String str = null;
//------------Using Concatenation operator-------------
long time1 = System.currentTimeMillis();
long freeMemory1 = Runtime.getRuntime().freeMemory();
for(int i=0; i<100000; i++){
str = "Hi";
str = str+" Bye";
}
long time2 = System.currentTimeMillis();
long freeMemory2 = Runtime.getRuntime().freeMemory();
long timetaken1 = time2-time1;
long memoryTaken1 = freeMemory1 - freeMemory2;
System.out.println("Concat operator :" + "Time taken =" + timetaken1 +
" Memory Consumed =" + memoryTaken1);
//------------Using Concat method-------------
long time3 = System.currentTimeMillis();
long freeMemory3 …Run Code Online (Sandbox Code Playgroud)