站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Java 专题String与StringBuffer

String与StringBuffer

摘要: String与StringBuffer

</td> </tr> <tr> <td width="511" height="35" valign="top" class="ArticleTeitle">

String的创建

String s = "hello";
JVM先根据内容"hello"查找对象,如果没有找到,则在heap(堆)上创建新对象,并将其赋予s1,否则使用已经存在的对象

String s = new String("hello");
JVM直接在heap上创建新的对象,所以在heap中会出现内容相同,地址不同的String对象

String的比较

"==" 比较地址
"equals" 比较内容

举例:
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");

s1 == s2; // true 地址相同
s1 == s3; // false 地址不同
s1.equals(s2); // true 内容相同
s1.equals(s3); // true 内容相同


intern() 方法

查找内容相同(equals())的字符串

String s1 = "hello"; // hello不存在,jvm创建新对象 (1)

String s2 = new String("hello"); // 创举新对象 (2),这时heap中存在两个内容为hello的对象

s1 == s2; // false // 地址不同

s1.equals(s2); // true // 内容相同

s2 = s2.intern(); // true // 找到对象(1) 并赋予s2

s1 == s2; // true !! // 注意:此时s1,s2同指向(1)


效率:String 与 StringBuffer

情景1:
(1) String result = "hello" + " world";
(2) StringBuffer result = new String().append("hello").append(" world");

(1) 的效率好于 (2),不要奇怪,这是因为JVM会做如下处理
编译前 String result = "hello" + " world";
编译后 String result = "hello world";

情景2:
(1) public String getString(String s1, String s2) {
return s1 + s2;
}
(2) public String getString(String s1, String s2) {
return new StringBuffer().append(s1).append(s2);
}

(1) 的效率与 (2) 一样,这是因为JVM会做如下处理
编译前 return s1 + s2;
编译后 return new StringBuffer().append(s1).append(s2);

情景3:
(1) String s = "s1";
s += "s2";
s += "s3";
(2) StringBuffer s = new StringBuffer().append("s1").append("s2").append("s3");

(2) 的效率好于(1),因为String是不可变对象,每次"+="操作都会造成构造新的String对象

情景4:
(1) StringBuffer s = new StringBuffer();
for (int i = 0; i < 50000; i ++) {
s.append("hello");
}

(2) StringBuffer s = new StringBuffer(250000);
for (int i = 0; i < 50000; i ++) {
s.append("hello");
}

(2) 的效率好于 (1),因为StringBuffer内部实现是char数组,默认初始化长度为16,每当字符串长度大于char数组长度的时候,JVM会构造更大的新数组,并将原先的数组内容复制到新数组,(2)避免了复制数组的开销

关键点
1). 简单的认为 .append() 效率好于 "+" 是错误的!
2). 不要使用 new 创建 String
3). 注意 .intern() 的使用
4). 在编译期能够确定字符串值的情况下,使用"+"效率最高
5). 避免使用 "+=" 来构造字符串
6). 在声明StringBuffer对象的时候,指定合适的capacity,不要使用默认值(18)
7). 注意以下二者的区别不一样
String s = "a" + "b";
String s = "a";
s += "b";

</td> <td width="173" valign="top" class="ArticleTeitle"> </td> </tr> <tr> <td height="25" colspan="2" valign="top" class="ArticleTeitle">


↑返回目录
前一篇: 在Java程序中运行外部类文件
后一篇: 异常回调