Spring

stream API와 for-loop 성능차이

ZzangHo 2022. 2. 7. 23:14
728x90

나의 경우 stream API를 많이 써보지 않았는데 이번에 신기한것을 발견하였다.

간만에 프로그래머스에서 코딩테스트를 보는데 stream API를 썼을 때 효율성 테스트를 통과하지 못하길래 열심히 구글링을 해보니 stream API가 for-loop문보다 더 성능이 안 좋다는것이 아니겠는가?

 

한번 테스트를 해보자

package level1;

import java.util.Arrays;
import java.util.Random;

public class PerfomanceTest {
    public static void main(String[] args) {
        int[] arr = new int[100];
        long start;
        long end;
        Random rd = new Random();

        // init
        for (int i = 0; i < arr.length; i++) {
            arr[i] = rd.nextInt(100) + 1;
        }

        // 1단계 for-loop
        int max_value = 0;
        start = System.nanoTime();
        for (int i=0; i<arr.length; i++) {
            if (max_value < arr[i]) max_value = arr[i];
        }
        end = System.nanoTime();
        System.out.println("수행시간: " + (end - start) + " ns");
        System.out.println("1단계 max : " + max_value);

        start = System.nanoTime();
        max_value = Arrays.stream(arr).max().getAsInt();
        end = System.nanoTime();
        System.out.println("수행시간: " + (end - start) + " ns");
        System.out.println("2단계 max : " + max_value);
    }
}

 

소스코드의 경우 간단하다. 

1부터 100까지의 숫자를 랜덤으로 생성한 배열을 for-loop문과 streamAPI를 사용하여 max값을 뽑는 예제이다.

위의 소스 코드를 실행을 해보면 아래와 같이 결과가 나온다.

수행시간: 2000 ns
1단계 max : 100
수행시간: 1568900 ns
2단계 max : 100
Process finished with exit code 0

역시 기존 for-loop문이 더 빠르다.

 

왜 그럴까??

 

관련 참고자료를 인용하면, 단순 for-loop의 경우 오버헤드가 없는 단순한 인덱스 기반 메모리 접근이기 때문에 Stream을 사용했을 때보다 더 빠르다고 합니다. (“It is an index-based memory access with no overhead whatsoever.”)

또, 컴파일러의 관점에서 오랫동안 유지해온 for-loop의 경우 최적화를 할 수 있으나 반대로 비교적 최근에 도입된 스트림의 경우 for-loop와 같은 정교한 최적화를 수행하지 않는다고 한다.

 

stream API를 많이 써보지 않아서 이번에 한번 써보았는데 신기하면서도 무작정 for문을 대체하듯이 막 쓰면은 안되겠구나를 느낌..

'Spring' 카테고리의 다른 글

application.yml 여러개로 나누기  (0) 2022.12.14
SpringBatch 전용 DB 테이블  (0) 2022.02.07
SpringBatch  (0) 2022.02.07
application.yml로 환경 나누기  (0) 2022.01.28