티스토리 뷰

https://gogogohigher.tistory.com/7 이 포스트를 먼저 참고하면 좋다.

 

자바의 입출력은 모두 java.io패키지에서 관리한다.

그 중 바이트의 출력 스트림에 관한 모든 클래스의 부모 클래스는 OutputStream 클래스이다.

public abstract class OutputStream
extends Object
implements Closeable, Flushable

이 외에도 OutputStream을 상속하는 클래스는 무지 많다..!

 

우리가 자바에서 출력할 때 사용하는 System.out도 OutputStream의 하위 클래스이다.

System클래스에 가보면 out이 PrintStream형으로 선언되어 있는 것을 알 수 있다.

OutputStream의 Method들

public abstract void write(int b) throws IOException

(abstract 메소드이기 때문에 구현 클래스에서 구현해 주어야 한다!)

한 바이트를 읽어서 output stream에 기록한다.

 

public void write(byte[] b) throws IOException

b.length 바이트 만큼 바이트들을 output stream에 기록한다. 

write (b, 0, b.length) 와 같다.

 

public void write (byte[] b, int off, int len) throws IOException

 

b[offset] ~ b[offset + len -1] 의 바이트들을 output stream에 기록한다.

배열 안의 각 바이트를 output stream에다 기록할 때 wite를 호출하여 기록한다.

오라클 문서에 의하면 구현 클래스에서는 이 메소드를 보다 더 효율적으로 오버라이딩 하길 권고하고 있다.

public void flush() throws IOException

output stream을 flush하고 버퍼에 있는 출력 바이트들을 output stream에 기록한다.

 

public void close() throws IOException

output stream과 이 스트림에 관련된 시스템 자원들을 닫는다. 


Single byte 출력 VS Byte Array 출력

byte 문자열을 10만 라인을 출력하여 single byte로 출력했을 때와 byte array로 출력했을 때를 비교해보려 한다.

Single byte 코드

import java.io.IOException;
import java.io.OutputStream;

public class SingleByte {
    public static void main(String[] args) {
        long time = 0;
        long startTime = 0;
        long endTime = 0;

        int firstPrintableCharacter = 33;
        int numberOfPrintableCharacters = 94;
        int numberOfCharacterPerLine = 72;

        int start =firstPrintableCharacter;
        int count =0;

        OutputStream out = System.out;

        try{
            while(count < 100000){
                startTime = System.nanoTime();
                for (int i = start; i < start + numberOfCharacterPerLine; i++) {
                    out.write((byte) ((i - firstPrintableCharacter) % numberOfPrintableCharacters + firstPrintableCharacter));
                }
                out.write((byte) '\r');
                out.write((byte) '\n');

                start = ((start + 1) - firstPrintableCharacter) % numberOfPrintableCharacters + firstPrintableCharacter;

                endTime = System.nanoTime();
                time += endTime - startTime;
                
                count++;
            }
        }catch (IOException e){
            System.err.println("IOException");
        }

        System.out.println("SingleByte everage time = " + time/100000);
    }
}

 

byte array 코드

 

import java.io.IOException;
import java.io.OutputStream;

public class ByteArray {
    public static void main(String[] args) {
        long startTime = 0;
        long endTime = 0;

        int firstPrintableCharacter = 33;
        int numberOfPrintableCharacters = 94;
        int numberOfCharacterPerLine = 72;

        //byte array 생성
        byte[] byteLine = new byte[(numberOfCharacterPerLine + 2) * 100000];
        int count =0;
        int start =firstPrintableCharacter;
        int index = 0;
        while(count < 100000){
            for (int i = start; i < start + numberOfCharacterPerLine; i++) {
                byteLine[index++] = (byte) ((i - firstPrintableCharacter) % numberOfPrintableCharacters + firstPrintableCharacter);
            }
            byteLine[index++] = ((byte) '\r');
            byteLine[index++] = ((byte) '\n');
            start = ((start + 1) - firstPrintableCharacter) % numberOfPrintableCharacters + firstPrintableCharacter;
            count++;
        }

        count =0;
        start =firstPrintableCharacter;

        OutputStream out = System.out;

        try{
            startTime = System.nanoTime();
            out.write(byteLine);
            endTime = System.nanoTime();
        }catch (IOException e){
            System.err.println("IOException");
        }
        System.out.println("ByteArray everage time = " + (endTime - startTime)/100000);
    }
}

비교

여러번 실행해본 결과, 10만번을 평균 내었을 때 byte array로 출력한 것이 현저히 빠르다!

single byte때 for문 시간을 고려하지 않아서 일까 해서 안에서 시간을 쟀을 때도 비교를 했지만 시간은 오히려 더 느려졌었다....

 

그래서 구현 클래스에서 더 효율적으로 오버라이딩 한건가 싶어 PrintStream과 FilterOutputStream을 확인해 보았다.

분명 배열 인덱스 마다 write()를 호출하고 있는데 왜 빠른거죠...?

'Language > Java' 카테고리의 다른 글

[Java] 바이트 기반 스트림 과 문자 기반 스트림  (0) 2022.09.25
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함