20180914-Java实例03

 


Java 实例 – 字符串性能比较测试


以下实例演示了通过两种方式创建字符串,并测试其性能:


// StringComparePerformance.java 文件

public class StringComparePerformance{
public static void main(String[] args){
long startTime = System.currentTimeMillis();
for(int i=0;i<50000;i++){
String s1 = "hello";
String s2 = "hello";
}

long endTime = System.currentTimeMillis();

System.out.prinln("通过String 关键字创建字符串"
+":" +(endTime - startTime) + "毫秒");

long startTime1 = System.currentTimeMillis();
for(int i=0;i<50000;i++){
String s3 = new String("hello");
String s4 = new String("hello");
}

long endTimel = System.currentTimeMillis();
System.out.println("通过 String 对象创建字符串"
+":" +(endTimel - startTimel) + "毫秒"
);

}

}

 

以上代码实例输出结果为:

通过 String 关键词创建字符串 : 6 毫秒
通过 String 对象创建字符串 : 14 毫秒

 

 

 


Java 实例 – 字符串优化

 

 

以下实例演示了通过 String.intern() 方法来优化字符串:


// StringOptimization.java 文件


public class StringOptimization{
public static void main(String[] args){
String variables[] = new String[50000];
for(int i=0;i<50000;i++){
variables[i] = "s" + i;
}
long startTime() = System.currentTimeMillis();

for(int i=0;i<50000;i++){
variables[i] = "hello";
}

long endTime() = System.currentTimeMillis();
System.out.println("Creation time"
+ " of String literals : "+ (endTime0 - startTime0)
+ " ms")

long startTimel = System.crrentTimeMillis();
for(int i=0;i<50000;i++){
variables[i] = new String("hello");
}

long endTimel = System.currentTimeMillis();
System.out.println("Creation time of"
+ " String objects with 'new' key word : "
+ (endTime1 - startTime1)
+ " ms");

long startTime2 = System.currentTimeMillis();
for(int i=0;i<50000;i++){
variables[i] = new String("hello");
variables[i] = variables[i].intern();
}

long endTime2 = System.currentTimeMillis();
System.out.println("Creation time of"
+ " String objects with intern(): "
+ (endTime2 - startTime2)
+ " ms");
}
}

 

以上代码实例输出结果为:


Creation time of String literals : 0 ms
Creation time of String objects with 'new' key word : 31 ms
Creation time of String objects with intern(): 16 ms

 

posted @ 2018-10-19 18:19  Alanf  阅读(125)  评论(0编辑  收藏  举报