连接运算符(+)与concat() [英] Concatenation operator (+) vs. concat()

查看:121
本文介绍了连接运算符(+)与concat()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于字符串连接,我们可以使用 concat()或concat运算符(+)

For string concatenation we can use either the concat() or concat operator (+).

我已经尝试了以下性能测试,发现 concat()更快,并且是一种内存有效的字符串连接方式。

I have tried the following performance test and found concat() is faster and a memory efficient way for string concatenation.

字符串连接比较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 = Runtime.getRuntime().freeMemory();
for(int j=0; j<100000; j++){
    str = "Hi";
    str = str.concat(" Bye");
}
long time4 = System.currentTimeMillis();
long freeMemory4 = Runtime.getRuntime().freeMemory();
long timetaken2 = time4-time3;
long memoryTaken2 = freeMemory3 - freeMemory4;
System.out.println("Concat method  :" + "Time taken =" + timetaken2 +
                   " Memory Consumed =" + memoryTaken2);

结果

Concat operator: Time taken = 31; Memory Consumed = 2259096
Concat method  : Time taken = 16; Memory Consumed = 299592

如果 concat()比运算符快,那么我们何时应该使用连接运算符(+)

If concat() is faster than the operator then when should we use concatenation operator (+)?

推荐答案

concat方法总是生成一个带有连接结果的新String。

The concat method always produces a new String with the result of concatenation.

plus运算符由StringBuilder创建支持,附加所需的所有String值,并进一步调用toString()。

The plus operator is backed by StringBuilder creation, appending all String values you need and further toString() calling on it.

因此,如果你需要连接两个值,concat()将是更好的选择。如果需要连接100个值,则应使用加号运算符或显式使用StringBuilder(例如,如果要在循环中追加)。

So, if you need to concatenate two values, concat() will be better choice. If you need to concatenate 100 values, you should use the plus operator or explicitly use StringBuilder (e.g. in case of appending in a cycle).

这篇关于连接运算符(+)与concat()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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