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
. 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.
No comments:
Post a Comment