Study/Java

[TEST] File Read Performance (파일 읽기 처리 속도)

LoonyHyun 2020. 12. 17. 12:30
반응형

JAVA 에서 파일 읽기를 하면 대게 FileReader, FileInputStream, RandomAccessFile 을 사용한다.

 

파일 읽기 시 어떤 것을 쓰던 상관은 없지만

프로세스 처리 속도를 위해 빠르게 처리하기 위해서 Stream 을 많이 쓰게 된다.

RandomAccessFile 은 Stream 을 기반으로 만들어진 클래스이기에 FileInputStream 과 처리속도는 비슷할 것으로 예상된다.

 

각자의 처리 속도를 비교해 봤다.

비교 시 모두 같은 파일을 사용했으며,

파일크기는 300KB 정도이며,

개인 PC로 진행했기에 처리 속도는 각자 다르게 나타날 수 있다.

처리 속도는 ms 기준이다.

  FileReader RandomAccessFile FileChannel FileInputStream
1회 8 0 9 0
100회 100 11 18 10
1000회 808 87 116 67
10000회 7971 632 952 679

위 표를 보면 알 수 있듯이 Stream 기반의 클래스가 처리 속도가 빠르다.

간단한 테스트로서 JAVA 프로세스 개발 시 FileReader 를 사용하는 것은 괜찮겠지만,

현실적으로 거의 모든 프로세스에서 사용하기 어렵다고 생각하면 된다.

 

아래는 사용한 각각의 샘플 소스 이다.

----------------------------------------------------------
FileReader
----------------------------------------------------------
		FileReader fr = null;
		
		try {
			fr = new FileReader(FILE_PATH);
			
			char[] cbuf = new char[1024];
			while(fr.read(cbuf) > 0) {
				
			}
			
			
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(fr != null) {
					fr.close();
				}
			}catch(IOException e) {
				e.printStackTrace();
			}
		}


----------------------------------------------------------
RandomAccessFile
----------------------------------------------------------
		RandomAccessFile raf = null;
		
		try {
			raf = new RandomAccessFile(FILE_PATH, "r");
			
			long fileLength = raf.length();
			byte[] bb = new byte[(int)fileLength];
			raf.read(bb);
			raf.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(raf != null) {
					raf.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}


----------------------------------------------------------
FileChannel
----------------------------------------------------------
		Path path = Paths.get(FILE_PATH);
		if(!Files.exists(path)) {
			return;
		}
		
		FileChannel channel = null;
		try {

			channel = FileChannel.open(path, StandardOpenOption.READ);
			long fileLength = channel.size();
			ByteBuffer bb = ByteBuffer.allocate((int)fileLength);
			channel.read(bb);
			bb.flip();
			channel.close();
			
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(channel != null) {
					channel.close();
				}
			}catch(IOException e) {
				e.printStackTrace();
			}
		}


----------------------------------------------------------
FileInputStream
----------------------------------------------------------
		FileInputStream fis = null;

		try {
			fis = new FileInputStream(FILE_PATH);
			
			byte[] bb = new byte[fis.available()];
			while(fis.read(bb) > 0) {
				
			}
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(fis != null) {
					fis.close();
				}
			}catch(IOException e) {
				e.printStackTrace();
			}
		}