【发布时间】:2012-02-29 19:20:36
【问题描述】:
我们正在与一位朋友讨论有关 java 代码设计和效率的问题。
他认为,出于性能原因以及覆盖时的类一致性保护,方法最好是私有的。
我认为最好保护方法以实现完全可定制性,并避免在用户想要更改其部分行为时立即修改和发布 API 浪费时间。
我们知道对composition over inheritance的偏好,所以这里我主要关注性能比较。
一个简单的测试(见下文)证明父类具有受保护方法的扩展类并不比父类具有私有方法的扩展类慢。它甚至有时(我不太了解性能变化)更快。
elapsed:8051733.063 microseconds for A (private)
elapsed:8036953.805 microseconds for B (protected)
您认为下面提到的测试是否足够稳健以进行比较?
public class VerifPerfProtected {
public static void main(String[] args) {
int ncalls = 1000000000; //10^9
ChildrenClassA a = new ChildrenClassA();
ChildrenClassB b = new ChildrenClassB();
long start = System.nanoTime();
a.manyCalls(ncalls);
long stop = System.nanoTime();
System.out.println("elapsed:" + (stop - start)/1000.0 + " microseconds for A (private)");
start = System.nanoTime();
b.manyCalls(ncalls);
stop = System.nanoTime();
System.out.println("elapsed:" + (stop - start)/1000.0 + " microseconds for B (protected)");
}
public static class ParentClassA{
public void manyCalls(int n){
for (int i = 0; i < n; i++) {
callAmethod();
}
}
public void callAmethod(){
aPrivateMethod();
}
private void aPrivateMethod(){
int a=0;
for (int i = 0; i < 5; i++) {
a++;
}
}
}
public static class ParentClassB{
public void manyCalls(int n){
for (int i = 0; i < n; i++) {
callAmethod();
}
}
public void callAmethod(){
aProtectedMethod();
}
protected void aProtectedMethod(){
int a=0;
for (int i = 0; i < 5; i++) {
a++;
}
}
}
public static class ChildrenClassA extends ParentClassA{
}
public static class ChildrenClassB extends ParentClassB{
}
}
【问题讨论】:
-
你打了两次电话。错字还是错误?
-
我的错误...我更新了代码和性能结果。谢谢。