java中string和stringbuffer

 String s="Hello";
s+="World";
//以上代码等价与下述代码
StringBuffer sb=new StringBuffer(s);
sb.append("world");
s=sb.toString();

StringBuffer会产生许多临时对象,从而导致程序的执行效率变低,但是在当一个字符串需要经常被修改的时,使用StringBuffer比使用String好很多。

但是 StringBuffer的效率高于String。

public class Test
{
public static void testString()
{
String s="hello";
String s1="world";
long start=System.currentTimeMillis();
for(int i=0;i<10000;i++)
{
s+=s1;}
long end =System.currentTimeMill();
long runTime=(end-start);
syso(runTime);


}

}

评论

h
hw_7864

⭐️ Admin快速开发: https://show.cool-admin.com/

赞 0
h
hw_7864

⭐️ 官方文档: https://cool-js.com

赞 0
h
hw_7864

⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld

赞 0