Avatar
1
Nguyễn Thái Sơn Professional
Nguyễn Thái Sơn Professional
có nên dùng stream thay cho for loop
Anh Dũng ơi, em hay dùng vòng lặp for thay vì stream ở java 8 , em cũng code theo OOP truyền thống, không dùng các functional ở Java 8 vì nó dễ nhìn, fresher và junior có thể đọc hiểu. Em đã tìm nhiều topic compare Stream và For loop nhưng performance không chênh nhau nhiều anh ạ
  • Answer
Remain: 5
1 Answer
Avatar
monkey Enlightened
monkey Enlightened
Anh vừa thử khởi tạo 1 list với 1 triệu phần tử thế này:
final List list = new ArrayList();
for (int i = 0 ; i < 1000000 ; ++i) {
    list.add(i);
}
Và thực hiện việc copy với 3 loại lăp:
  1. foreach
    final List forLoopCopy = new ArrayList();
    final long forLoopStartTime = System.currentTimeMillis();
    for (Integer item : list) {
        forLoopCopy.add(item);
    }
    final long forLoopElapsed = System.currentTimeMillis() - forLoopStartTime;
    System.out.println("for loop elapsed: " + forLoopElapsed);
    
  1. for index
    final List forIndexCopy = new ArrayList();
    final long forIndexStartTime = System.currentTimeMillis();
    for (int i = 0 ; i < list.size() ; ++i) {
        forIndexCopy.add(list.get(i));
    }
    final long forIndexElapsed = System.currentTimeMillis() - forIndexStartTime;
    System.out.println("for index elapsed: " + forIndexElapsed);
    
  1. Và stream
    final List streamCopy = new ArrayList();
    list.forEach(it -> streamCopy.add(it)); // warm up chương trình
    final long streamStartTime = System.currentTimeMillis();
    list.stream().forEach(it ->
        streamCopy.add(it)
    );
    final long streamElapsed = System.currentTimeMillis() - streamStartTime;
    System.out.println("stream elapsed: " + streamElapsed);
    
Và kết quả anh có:
for loop elapsed: 16
for index elapsed: 15
stream elapsed: 41
mapfilterparallelStream
cũng rất tiện nên có nhiều người dùng thích dùng stream hơn. Anh thì thì không thích stream lắm.
  • 0
  • Reply