My teacher says that we can use final
to improve efficiency. I tried to do the test, but I find that adding a final method modifier can actually reduce the efficiency.
My test is like this:
ClassTest1:
public class ClassTest1 {
public final String getName() {
return name;
}
public final void setName(String name) {
this.name = name;
}
private String name;
}
ClassTest2:
public class ClassTest2 {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
Main Test Method:
public static void main(String[] args) {
ClassTest1 ct1=new ClassTest1();
ClassTest2 ct2=new ClassTest2();
Long t1=System.currentTimeMillis();
for (int i = 0; i <1000000 ; i++) {
ct1.getName();
}
Long t2=System.currentTimeMillis();
for (int i = 0; i <1000000 ; i++) {
ct2.getName();
}
Long t3=System.currentTimeMillis();
System.out.println("add final decorate cost time:"+(t2-t1));
System.out.println("not add final decorate cost time:"+(t3-t2));
}
Why does adding final
cost more time than not adding the final method?