标签:uil 创建 cal .com instance private method port sys
import java.util.Calendar;
import java.util.Date;
public class Person {
private final Date birthDate = new Date();
//重复创建对象
public boolean slow () {
Calendar cal = Calendar.getInstance();
cal.set(2000, Calendar.JANUARY, 1, 0, 0, 0);
Date start = cal.getTime();
cal.set(2017, Calendar.JANUARY, 1, 0, 0, 0);
Date end = cal.getTime();
return birthDate.compareTo(start) >= 0
&& birthDate.compareTo(end) < 0;
}
//改进后
private static final Date START;
private static final Date END;
static {
Calendar cal = Calendar.getInstance();
cal.set(2000, Calendar.JANUARY, 1, 0, 0, 0);
START = cal.getTime();
cal.set(2017, Calendar.JANUARY, 1, 0, 0, 0);
END = cal.getTime();
}
public boolean faster () {
return birthDate.compareTo(START) >= 0
&& birthDate.compareTo(END) < 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//较好
Date start = new Date();
Person person = new Person();
for(int i = 0,max = 1000000; i < max; i++) {
person.faster();
}
Date end = new Date();
System.out.println("用时: " + (end.getTime() - start.getTime()));
//较差
start = new Date();
for(int i = 0,max = 1000000; i < max; i++) {
person.slow();
}
end = new Date();
System.out.println("用时: " + (end.getTime() - start.getTime()));
//较差
start = new Date();
String sum = "";
for(int i = 0,max = 100000; i < max; i++) {
sum += " ";
}
end = new Date();
System.out.println("用时: " + (end.getTime() - start.getTime()));
//较好
start = new Date();
StringBuilder sb = new StringBuilder();
for(int i = 0,max = 100000; i < max; i++) {
sb.append(" ");
}
end = new Date();
System.out.println("用时: " + (end.getTime() - start.getTime()));
}
}
输出结果 :
用时: 5
用时: 683
用时: 4301
用时: 3
标签:uil 创建 cal .com instance private method port sys
原文地址:http://www.cnblogs.com/mzxl1987/p/7803452.html