[java] 문자열(String) 나누기, Split VS SubString

program/java 2012. 10. 5. 11:21
반응형

Q. "|"로 구분된 문자열(String)을 "|" 단위로 일부 추출하여 List 에 저장한다.
"|" 로 문자열을 자를때 Split과 SubString 의 속도를 비교한다.

ex) 100100|017|1|서울체신청|Y|


소스코드

import java.io.*;
import java.util.ArrayList;

public class StrSplitVsSubString
{
	public static void main( String[] args ) throws Exception
	{
		BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream( "post.txt" ), "euc-kr" ) );

		int cnt = 0;
		int totCnt = 0;
		String s;

		ArrayList list = new ArrayList();

		long start = System.nanoTime();
		while( ( s = reader.readLine() ) != null )
		{
			cnt++;
			if( false )
			{
				String[] arr = s.split( "|" );
				list.add( arr[3] );
			}
			else
			{
				String no = s.substring( 0, 6 );
				int index1 = s.indexOf( '|', 11 );
				int index2 = s.indexOf( '|', index1 + 1 );
				String address = s.substring( index1 + 1, index2 );
				list.add( address );
			}
		}

		if( cnt > 0 )
			System.out.println( "\n\nTotal : " + ( totCnt + cnt ) );

		long end = System.nanoTime();
		System.out.println( ( end - start ) + "(ns)" );
	}
}



결과


 Split

SubString 

1018486826(ns) => 1.01초

1019984754(ns) => 1.01초

1023826810(ns) => 1.02초

1021068796(ns) => 1.02초

1031451956(ns) => 1.03초

163028956(ns) => 0.16초

172060749(ns) => 0.17초

163285509(ns) => 0.16초

166215880(ns) => 0.16초

165033753(ns) => 0.16초



결론


1. Split

Split은 Pattern.compile 객체를 new 로 생성하여 문자열을 자른다.

결과 값을 String[] 배열을 받아오기 때문에, String 배열 또한 생성해야 함으로 더 느려진다.


2. SubString

SubString 은 Split 보다 1/10 초 정도 줄어든 현상을 볼 수 있다.

SubString은 String의 value[] 라는 배열을 참조하여, offset(순번)과 count(총개수)만을 가지고 있다.

그러므로 객체를 생성하지 않은 SubString 이 보다 빠르다.


※ 성능을 고려하여 되도록 SubString을 쓰자.

반응형