我试图找到lambda的特性使其与传统方法不同。为了找到lambda表达式和Anonymous类之间的时间消耗,我创建了一个示例代码,发现lambda的时间消耗太高。我对么?
public class Test {
public static void main(String[] args) {
long str = System.nanoTime();
usingLambda();
long end = System.nanoTime();
System.out.println("Differnce: usingLambda: " + (end - str) + "ns");
long str2 = System.nanoTime();
usingAnonymousClass();
long end2 = System.nanoTime();
System.out.println("Differnce usingAnonymousClass: " + (end2 - str2) + "ns");
}
private static void usingLambda() {
Messagable lambda = () -> {
System.out.println("Test.callByLambda()");
};
lambda.sendMessage();
}
private static void usingAnonymousClass() {
Messagable anonymous = new Messagable() {
@Override
public void sendMessage() {
System.out.println("Test.usingAnonymousClass()");
}
};
anonymous.sendMessage();
}
}
interface Messagable {
public void sendMessage();
}
输出:
ParallelArraySorting.callByLambda()
区别:使用兰巴达: 46650876ns
ParallelArraySorting.usingAnonymousClass()
使用匿名类的差异: 447249ns