1

I have tried only with 6 elements as I didn't have much data. I ran each method thrice

When I ran basic for loop, it took very less time compare to parallel stream. Is it due to less number or record. If yes, can I get any graph where I can see after how may records parallel stream can overtake basic for loop for basic opearion.

 long startTime = System.nanoTime(); // 222436 331094 316872ns for (int i = 0; i < employeeOtps.size(); i++) { Employee emp = employees.get(i); EmployeeOtp employeeOtp = employeeOtps.get(i); emp.setMobileNo(employeeOtp.getReqValue()); employees.set(i, emp); } // OR this one // 3071437 3879830 3177251ns IntStream.range(0, employeeOtps.size()).parallel.forEach(i -> { EmployeeMaster emp = employees.get(i); EmployeeOtp employeeOtp = employeeOtps.get(i); emp.setMobileNo(employeeOtp.getReqValue()); employees.set(i, emp); }); // OR this one //8727341 14350819 6088261ns IntStream.range(0, employeeOtps.size()).forEach(i -> { EmployeeMaster emp = employees.get(i); EmployeeOtp employeeOtp = employeeOtps.get(i); emp.setMobileNo(employeeOtp.getReqValue()); employees.set(i, emp); }); long totalTime = (System.nanoTime() - startTime); 

I ran one by one and recorded time.

for loop:- 222436, 331094, 316872 ns

stream w/o parallel:- 3071437, 3879830, 3177251 ns

stream with parallel:- 3071437, 3879830, 3177251 ns

less time order wise for size = 6

basic for loop (290ms) < intstream parallel(3376ms) < intsream(9722ms)

4
  • 1
    There is overhead to setting up, starting, joining and gathering the results for multiple threads. TANSTAAFL Commented Dec 10, 2019 at 6:16
  • 1
    Parallel stream usually use when you need some kind of side effect, especially is IO like network call. For you use case, with a small of list of items, parallel stream will be slower becuz its had an overhead to use ForkJoinPool. And your code is kinda weird, to be honest, the benchmark usually difference about 100~200ms. In your case its 10-30 times slower. Dunno what your set method is doing. Commented Dec 10, 2019 at 6:23
  • 1
    Besides the deficits mentioned in the other comments about using parallel streams for small collections, your benchmarks are flawed and are not taking JIT compilation into account. When running the methods with the stream, a lot more code needs to be interpreted/JITted which slows down things further. Writing meaningful benchmarks is hard, but one option to avoid common pitfalls is to use something like JMH Commented Dec 10, 2019 at 6:31
  • 1
    Also worth reading How do I write a correct micro-benchmark in Java? Commented Dec 10, 2019 at 8:26

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.