以下代码测量从接口处理程序100次调用方法句柄(对象o)所花费的时间(是的,它的质量差异分析):
package test; import java.util.LinkedList; public class Test { static int i = 0; private interface Handler { public void handle(Object o); } private static class SuperHandler implements Handler { public void handle(Object o) { i += 1; } } private static class NoSuperHandler implements Handler { public void handle(Object o) { i += 1; } } private static class LulSuperHandler implements Handler { public void handle(Object o) { i += 1; } } private static class LilSuperHandler implements Handler { public void handle(Object o) { i += 1; } } private static class LolSuperHandler implements Handler { public void handle(Object o) { i += 1; } } private static class LalSuperHandler implements Handler { public void handle(Object o) { i += 1; } } private static class LylSuperHandler implements Handler { public void handle(Object o) { i += 1; } } private static class LzlSuperHandler implements Handler { public void handle(Object o) { i += 1; } } public static void main(String[] args) { LinkedList<Handler> ll = new LinkedList<Handler>(); for(int j = 0; j < 100; j++) { if((j % 8) == 0) ll.add(new SuperHandler()); if((j % 8) == 1) ll.add(new NoSuperHandler()); if((j % 8) == 2) ll.add(new LulSuperHandler()); if((j % 8) == 3) ll.add(new LilSuperHandler()); if((j % 8) == 4) ll.add(new LolSuperHandler()); if((j % 8) == 5) ll.add(new LalSuperHandler()); if((j % 8) == 6) ll.add(new LylSuperHandler()); if((j % 8) == 7) ll.add(new LzlSuperHandler()); } long begin = System.currentTimeMillis(); for(int j = 0; j < 1000000; j++) for(Handler h: ll) h.handle(null); System.out.println("time in ms: " + (System.currentTimeMillis() - begin)); System.out.println("i: " + i); } }
事实是,如果LinkedList只包含一种Handler,例如SuperHandler,则执行时间小于它们是2,3等不同种类的Handler.每次我在列表中添加一种新的Handler时,性能会下降.
例如,当我只改变这部分时,我获得了比上面更好的表现:
for(int j = 0; j < 100; j++) { if((j % 2) == 0) ll.add(new SuperHandler()); if((j % 2) == 1) ll.add(new NoSuperHandler()); }
这里有特殊的优化操作吗? JAVA架构中的性能会降低多少?我的测试是错误的,因为未使用的Handler被编译器“删除”或“隐藏”了吗?
(我正在使用Linux Ubuntu – 来自Oracle的JAVA 1.7)