본문 바로가기
프로그래밍 언어/Java

[예제] Java 입출력 속도 비교

by 까망 하르방 2021. 2. 18.
반응형

Java에서는 입·출력 하는 방식이 여러개 존재하는데, 이들의 속도를 비교하고자 합니다.

- System.out.println

- StringBuilder

- BufferedoutputStream

- BufferedWriter

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
 
public class Solution {
     public static void main(String[] args) throws Exception {
            long starttime = System.currentTimeMillis();
             
            // ################# System.out.println #################
            for (int i = 0; i < 100000; i++) {
               System.out.println( i );
            }
            long printlntime = System.currentTimeMillis();
            // ################# StringBuilder #################
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 100000; i++) {
                sb.append( i + "\n" );
            }
            System.out.print(sb.toString());
            long stringbuildertime = System.currentTimeMillis();
            // ################# BufferedoutputStream #################
            OutputStream out = new BufferedOutputStream( System.out );
            for (int i = 0; i < 100000; i++) {
                out.write((i + "\n").getBytes());
            }
            out.flush();
            long bufferedoutputtime = System.currentTimeMillis();
            // ################# BufferedWriter #################
            BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
            for (int i = 0; i < 100000; i++) {
                log.write(i + "\n");
            }
            log.flush();
            long bufferedwritertime = System.currentTimeMillis();
            System.out.println( "System.out.println: " + (printlntime - starttime) );
            System.out.println( "StringBuilder: " + (stringbuildertime - printlntime) );
            System.out.println( "BufferedoutputStream: " + (bufferedoutputtime - stringbuildertime) );
            System.out.println( "BufferedWriter: " + (bufferedwritertime - bufferedoutputtime) );
        }
}

[결과 中 일부]

BufferedWriter > StringBuilder > BufferedoutputStream > System.out.println

 

[BOJ] 백준 15552 빠른 A+B

출처: https://www.acmicpc.net/problem/15552  Input 5 1 1 12 34 5 500 40 60 1000 1000  Output 2 46 505 100 2000 Java에서 빠른 입출력을 보장받기 위해  BufferedoutputStream 이용 import java.io.Buf..

zoosso.tistory.com

 

반응형

'프로그래밍 언어 > Java' 카테고리의 다른 글

[Java] 기본 생성자 & 매개변수 생성자  (1) 2021.02.23
[Java] 생성자(Constructor)  (0) 2021.02.23
[Java] 객체 프로그래밍이란?  (0) 2021.02.23
[Java] ArrayList  (0) 2021.02.23
[Java] main 함수  (0) 2021.02.23

댓글