There was such a situation, parsing HTML using jsoup (1.7.3), the isUse method accepts Element and returns whether it is suitable for further work (there are a bunch of <article> tags). I am writing in Java 8 and I thought to use new ones:

 List<Element> news = items.stream().filter(e -> isUse(e)).collect(Collectors.toList()); 

Everything works, this code does not cause any questions, but I thought to compare with the usual cycle:

 List<Element> news = new ArrayList<>(); for (Element e : items) if (isPodcast(e)) news.add(e); 

And it turns out that option 2 approximately 2 - 1.5 times always works faster. Java version:

 java version "1.8.0" Java(TM) SE Runtime Environment (build 1.8.0-b132) Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode) 

OS: mac os x 10.9.3. I tried on Windows 7 x64 with java8u5.

PS It’s not that the difference in 60 - 80 ms strongly strains me, I just wonder why.

  • Sorry, but why are you using isUse() in one case and isUse() in the other? Is it because of this that the speed changes? - Jofsey

2 answers 2

The second option should be faster in theory, due to the smaller number of method calls, but not exactly 1.5-2 times. How did the performance compare? In 99.99999% of cases, the comparison method is incorrect.

  • it is quite possible that the measure is not so. just before and after the / stream loop, I call System.currentTimeMillis () and output the difference. - KoCaTKo
  • @KoCaTKo you got into these 99.99999% :) start from here and with the keywords youtube.com/watch?v=4p4vL6EhzOk But at least your option is statistically insignificant, due to the performance of only one repetition. - a_gura
  • thanks for the link) - KoCaTKo

The first call to the Stream API in the program is always very slow, because it is necessary:

  • Load many Stream API helper classes
  • Through the LambdaMetafactory, generate many anonymous classes from the lambda expressions that are used there.
  • If no lambdas have been used before, load the ASM classes that are used to generate anonymous classes.
  • All that stuff jit-compile.

This is all done once and can take about 50 ms. Repeated calls to the Stream API are much faster. Try to repeat the test several times.