본문

170420(목) - Streams <Laziness and Performance Optimization>

Streams


- Laziness Improves Performance

ㆍBigger data & Infinite streams를 다루는 동안 쓰면 효율적이다.

ㆍlazy processing은 process only on demand strategy를 base로 하고있다.



- Laziness and Java 8 Streams

ㆍ사용자가 실제로 사용하기 전까지 collection operations를 하지 않는다.


  1. //Created a Stream of a Students List
  2. //attached a map operation on it
  3. Stream<String> streamOfNames = students.stream()
  4. .map(student -> {
  5. System.out.println("In Map - " + student.getName());
  6. return student.getName();
  7. });
  8. //Just to add some delay
  9. for (int i = 1; i <= 5; i++) {
  10. Thread.sleep(1000);
  11. System.out.println(i + " sec");
  12. }
  13. //Called a terminal operation on the stream
  14. streamOfNames.collect(Collectors.toList());
  15. Output:
  16. 1 sec
  17. 2 sec
  18. 3 sec
  19. 4 sec
  20. 5 sec
  21. In Map - Tom
  22. In Map - Chris
  23. In Map - Dave



- Performance Optimization

various intermediate operations pipe를 만들고, terminal operations로 마무리한다.


  1. List<String> ids = students.stream()
  2. .filter(s -> {System.out.println("filter - "+s); return s.getAge() > 20;})
  3. .map(s -> {System.out.println("map - "+s); return s.getName();})
  4. .limit(3)
  5. .collect(Collectors.toList());
  6. Output:
  7. filter - 8
  8. map - 8
  9. filter - 9
  10. map - 9
  11. filter - 10    // didn't pass filter test
  12. filter - 11
  13. map - 11



- Short Circuit Methods

ㆍshort circuit 을 통해서 streams 처리를 최적화 한다.

조건이 만족되는 스트림을 조기 종료처리 해버림


  1. //List of names
  2. List<String> names = Arrays.asList(new String[]{"barry", " andy", "ben", "chris", "bill"});
  3. //map and filter are piped and the stream is stored
  4. Stream<String> namesStream = names.stream()
  5. .map(n -> {System.out.println("In map - " + n); return n.toUpperCase();})
  6. .filter(upperName -> {System.out.println("In filter - " + upperName);
  7. return upperName.startsWith("B");});



공유

댓글