Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

ParallelStream() is a faster way to read files while using Stream(). For this I have compared Stream and ParallelStream to their reference scenarios.

Difference: For Stream, it is a single-pipe serial Stream, which is unordered processing. ParallelStream handles multi-pipe parallel streams.

Code display:

I’m going to define an array of type Integer here, and I’m going to use LinkedList because it’s an insert.

public static List<Integer> buildIntLists() { long startLinked = System.currentTimeMillis(); List<Integer> linkedList =new LinkedList(); for (int a = 1; a <=10000 ; a++) { linkedList.add(a); } system.out.println (" Create LinkedList: "+ (system.currentTimemillis () -startlinked) + "ms"); return Collections.unmodifiableList(linkedList); }Copy the code

List<Integer> integerList = buildIntLists(); System. The out. Println (" print: "+ integerList. ToString ()); // First we use the traditional for loop (the primitive for loop is the most efficient), and then execute a sleep1ms code like this:  long start = System.currentTimeMillis(); for (int a = 0; a < integerList.size(); a++) { try { TimeUnit.MILLISECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }} system.out.println ("for loop: "+ (system.currentTimemillis () -start) + "ms"); // Create a sleep1ms file with the following code: start = system.currentTimemillis (); integerList.stream().forEach(r -> { try { TimeUnit.MILLISECONDS.sleep(1); } catch (Exception e) { e.printStackTrace(); }}); System.out.println("stream : " + (System.currentTimeMillis() - start) + "ms"); ParallelStream forEach = sleep1ms start = system.currentTimemillis (); integerList.parallelStream().forEach(r -> { try { TimeUnit.MILLISECONDS.sleep(1); } catch (Exception e) { e.printStackTrace(); }}); System.out.println("parallelStream : " + (System.currentTimeMillis() - start) + "ms");Copy the code

The result is as follows:

ParallelStream is not as efficient as ParallelStream. For example, my computer currently has 8 cores and its reading speed is around 196ms, so if my computer has 16 cores, its processing time will be significantly less than 196ms.

ParallelStream ParallelStream is much more efficient than Stream ParallelStream. ParallelStream ParallelStream ParallelStream ParallelStream ParallelStream ParallelStream ParallelStream ParallelStream ParallelStream ParallelStream ParallelStream Whether the current program needs to support parallelism. 2. Since multi-core is involved, multi-threaded relationship is bound to be designed, that is, whether there will be competition. 3. Whether the execution needs to be orderly. For all three of the above, ParallelStream can be used.