对比String、StringBuilder、StringBuffer时间效率
This commit is contained in:
parent
8f3a52c938
commit
00a5c68f22
59
src/chapter5/Example09.java
Normal file
59
src/chapter5/Example09.java
Normal file
@ -0,0 +1,59 @@
|
||||
package chapter5;
|
||||
|
||||
public class Example09 {
|
||||
private static final int TIMES = 100000;
|
||||
|
||||
public static void main(String[] args) {
|
||||
testString();
|
||||
testStringBuffer();
|
||||
testStringBuilder();
|
||||
test();
|
||||
}
|
||||
|
||||
// String时间效率
|
||||
public static void testString() {
|
||||
long start = System.currentTimeMillis();
|
||||
String str = "";
|
||||
for (int i = 0; i < TIMES; i++) {
|
||||
str += "test";
|
||||
}
|
||||
long end = System.currentTimeMillis();
|
||||
System.out.println("String测试耗时:" + (end - start) + "ms");
|
||||
}
|
||||
|
||||
// StringBuffer时间效率(线程安全)
|
||||
public static void testStringBuffer() {
|
||||
long start = System.currentTimeMillis();
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (int i = 0; i < TIMES; i++) {
|
||||
sb.append("test");
|
||||
}
|
||||
long end = System.currentTimeMillis();
|
||||
System.out.println("StringBuffer测试耗时:" + (end - start) + "ms");
|
||||
}
|
||||
|
||||
// StringBuilder时间效率(非线程安全)
|
||||
public static void testStringBuilder() {
|
||||
long start = System.currentTimeMillis();
|
||||
StringBuilder sb = new StringBuilder("hello");
|
||||
for (int i = 0; i < TIMES; i++) {
|
||||
sb.append("test");
|
||||
}
|
||||
long end = System.currentTimeMillis();
|
||||
System.out.println("StringBuilder测试耗时:" + (end - start) + "ms");
|
||||
}
|
||||
|
||||
public static void test() {
|
||||
String s1 = new String("abc");
|
||||
String s2 = new String("abc");
|
||||
System.out.println(s1.equals(s2)); // 打印结果为true
|
||||
StringBuffer sb1 = new StringBuffer("abc");
|
||||
StringBuffer sb2 = new StringBuffer("abc");
|
||||
System.out.println(sb1.equals(sb2)); // 打印结果为false
|
||||
StringBuilder sbr1=new StringBuilder("abc");
|
||||
StringBuilder sbr2=new StringBuilder("abc");
|
||||
System.out.println(sbr1.equals(sbr2)); // 打印结果为false
|
||||
|
||||
}
|
||||
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user