Sunday, August 26, 2018

for loop - What am i doing wrong with java 8 lambda Predicate?

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 ints 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...