【发布时间】:2016-03-22 04:07:28
【问题描述】:
This 不是我的问题的重复。我查了一下,我的是如何使用 proper Predicate,而 THAT 是关于 removeIf 和 remove 之间的区别。
我是初学 Java 程序员。
昨天,我尝试按照本教程进行操作https://dzone.com/articles/why-we-need-lambda-expressions
在我学会了如何使用 Lambda 表达式和 Predicate 之后,我编写了自己的代码来练习。
比如,如果(n % 3 == 0 || n % 5 == 0),求和所有数字。
这是我的代码。
public class Euler1Lambda {
long max;
public Euler1Lambda(long max) {
this.max = max;
}
public static boolean div3remainder0(int number) {
return number % 3 == 0;
}
public static boolean div5remainder0(int number) {
return number % 5 == 0;
}
public long sumAll() {
long sum = 0;
for(int i=1; i<max; i++) {
if (div3remainder0(i) ||div5remainder0(i)) {
sum += i;
}
}
return sum;
}
public long sumAllLambda(Predicate<Integer> p) {
long total = 0;
for (int i = 1; i< max; i++){
if (p.test(i)) {
total += i;
}
}
return total;
}
public static void main(String[] args) {
//conv
long startTime = System.currentTimeMillis();
for(int i = 0; i < 10; i++){
new Euler1Lambda(100000000).sumAll();
}
long endTime = System.currentTimeMillis();
long conv = (endTime - startTime);
System.out.println("Total execution time: " + conv);
//lambda
startTime = System.currentTimeMillis();
for(int i = 0; i < 10; i++){
new Euler1Lambda(100000000).sumAllLambda(n -> div3remainder0(n) || div5remainder0(n));
}
endTime = System.currentTimeMillis();
long lambda = (endTime - startTime);
System.out.println("Total execution time: " + lambda);
System.out.println("lambda / conv : " + (float)lambda/conv);
}
}
在这段代码中,进行了计时测试。
结果是这样的。
Total execution time conv: 1761
Total execution time lambda: 3266
lambda / conv : 1.8546281
如您所见,带有谓词的 lambda 表达式比简单的 for 循环慢。
我不知道为什么会这样。
我究竟做错了什么?还是只是谓词太慢了?
【问题讨论】:
标签: java for-loop lambda java-8 predicate