달력

3

« 2024/3 »

  • 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
  • 31

1. 문자열을 배열로 만든 후 for 문을 이용해서 List 에 add 하는 방법
2. Arrays.asList() 를 이용하는 방법

1번 예제 코드
  String str = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10";
  ArrayList<String> list = new ArrayList<String>();  
  String [] toColumnNm = str.split(",");
  for( int i = 0; i < toColumnNm.length; i++ ) {
   list.add(toColumnNm[i]);
  }

2번 예제 코드
String str = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10";
List<String> obj = Arrays.asList(str.split(","));

2번이 확실히 깔끔함.

그렇다면, 성능 비교.

성능 비교용 테스트 코드
public class ArrayToListTest {
 public static void main(String[] args) {
  StopWatch watch = new StopWatch();

  // 1번 방법 100만번 호출
  for(int i = 0 ; i < 1000000 ; i++) {
   doIt("1, 2, 3, 4, 5, 6, 7, 8, 9, 10");
  }
  // 소요 시간 출력
  System.out.println(watch.getDuration());

  // 2번 방법 100만번 호출
  for(int i = 0 ; i < 1000000 ; i++) {
   doIt2("1, 2, 3, 4, 5, 6, 7, 8, 9, 10");
  }
  // 소요 시간 출력
  System.out.println(watch.getDuration());
 }

 // 1번 방법
 public static void doIt(String str) {
  ArrayList<String> list = new ArrayList<String>();  
  String [] toColumnNm = str.split(",");
  for( int i = 0; i < toColumnNm.length; i++ ) {
   list.add(toColumnNm[i]);
  }
 }
 
 // 2번 방법
 public static void doIt2(String str) {
  List<String> obj = Arrays.asList(str.split(","));
 }
}

결과
2829
2625

2번이 쪼끔 빠르다.

끝.
:
Posted by 뽀기