What am i doing wrong with java 8 lambda Predicate<Integer>?
This question already has an answer here:
First of all, let's look at the scale of things. You're talking about a difference of about 1505 ms for 100000000 items, or about 15 nanoseconds per item. That overhead is not very substantial.
That said, the overhead is from autoboxing all those int
s into Integers
for the sake of the Predicate<Integer>
. Predicate::test
takes an Integer
, so p.test(i)
is really getting compiled down to p.test(Integer.valueOf(i))
. That method isn't super duper expensive, but it's not free. Apparently it takes about 15 nanoseconds on your computer.
If you use an IntPredicate
instead — which uses an int
primitive as its input, and thus avoids the boxing — you'll find that the difference between the direct and lambda-based approach is virtually gone.
Aside from that, there are the usual warnings about microbenchmarking in Java (warmup loops, using a framework like JMH, etc). There is a wealth of knowledge out there about that subject, and I strongly encourage you to read up on it if you want to continue benchmarking quick actions like this.
Performance and lambda can be tricky. In your case the use of wrapper type Integer and auto boxing slow down stuff.
Switch
public long sumAllLambda(Predicate<Integer> p)
to
public long sumAllLambda(IntPredicate p)
the results are almost the same
Total execution time conv: 3190
Total execution time lambda: 3037
lambda / conv : 0.95203763
链接地址: http://www.djcxy.com/p/86546.html
上一篇: 如何计算经过时间的加密和解密算法?