本博客每周五更新一次。
java语言final修饰符,可以修饰变量、方法和类,传言可以提升执行效率,实际情况到底如传言一样,写个程序测一下,一切自见分晓。
public final class StringUtilFinal {
/**
* 判断字符串是否为空
*/
public static boolean isEmpty(String str){
if(str==null||str.equals("")||str.length()<=0){
return true;
}
return false;
}
/**
* 判断字符串是否不为空
*/
public static boolean isNotEmpty(String str){
return !isEmpty(str);
}
}
public class StringUtilNoFinal {
/**
* 判断字符串是否为空
*/
public static boolean isEmpty(String str){
if(str==null||str.equals("")||str.length()<=0){
return true;
}
return false;
}
/**
* 判断字符串是否不为空
*/
public static boolean isNotEmpty(String str){
return !isEmpty(str);
}
}
public void testFinalClass() {
int size=1000000;
String data="12312312";
long start=System.currentTimeMillis();
for(int i=0;i<size;i++) {
StringUtilNoFinal.isNotEmpty(data);
}
System.out.println("No Final Cost Time:"+(System.currentTimeMillis()-start));
start=System.currentTimeMillis();
for(int i=0;i<size;i++) {
StringUtilFinal.isNotEmpty(data);
}
System.out.println("Final Cost Time:"+(System.currentTimeMillis()-start));
}
private Logger log = LoggerFactory.getLogger(this.getClass());
private final Logger logFinal = LoggerFactory.getLogger(this.getClass());
public void testLog() {
String data="~~我是日志~~";
int size=100000;
long start=System.currentTimeMillis();
for(int i=0;i<size;i++) {
log.info(data);
}
long value=System.currentTimeMillis()-start;
long startLong=System.currentTimeMillis();
for(int i=0;i<size;i++) {
logFinal.info(data);
}
System.out.println("Log No Final Cost Time:"+value);
System.out.println("Log Final Cost Time:"+(System.currentTimeMillis()-startLong));
}
public class NoFind {
private String name;
private String address;
private String code;
private String msg;
@Override
public String toString() {
return "Find [address=" + address + ", code=" + code + ", msg=" + msg + ", name=" + name + "]";
}
public void test() {
System.out.println("1231232");
}
}
public final class Find {
private String name;
private String address;
private String code;
private String msg;
@Override
public String toString() {
return "Find [address=" + address + ", code=" + code + ", msg=" + msg + ", name=" + name + "]";
}
public void test() {
System.out.println("1231232");
}
}
public void testClass() {
int size=1000000;
long start=System.currentTimeMillis();
Find find;
for(int i=0;i<size;i++) {
find=new Find();
find.toString();
}
System.out.println("No Final Cost Time:"+(System.currentTimeMillis()-start));
start=System.currentTimeMillis();
NoFind noFind;
for(int i=0;i<size;i++) {
noFind=new NoFind();
noFind.toString();
}
System.out.println("Final Cost Time:"+(System.currentTimeMillis()-start));
}
类 | 仅初始化 | 初始化+toString |
---|---|---|
find | 3ms | 30ms |
no-find | 5ms | 43ms |