자바스크립트 콜렉션 관련 팁 - JavaScript collection TIP


자바스크립트 콜렉션 관련 팁 - JavaScript collection TIP

   

    ① 배열의 이용

       

데이타의 개수나 사이즈가 변동하는 경우에만 Collection계통의 클라스를 사용하며그외에는 배열을 사용합니다.

      

    J2SE1.2이상에서의 Collection이용

 

JDK1.1까지는 Vector클래스나 Hashtable클래스가 편리했으나, 이러한 클래스는 메소드가 동기화(synchronized)

되어 있습니다. 따라서 동기화가 필요없는 경우에는 비효율적입니다.

J2SE1.2이상에서는 메소드가 동기화되어있지 않은 ArrayList클라스나 HashMap래스를 이용합니다.

          Vector클래스는 ArrayList Hashtable HashMap클래스로 바꿔이용합니다.

 

        ) Collection클래스 이용예

          

           Vector vector = new Vector();

           Hashtable table = new Hashtable();

 

        ) J2SE1.2이상 Collection클래스 이용예

         

           List list = new ArrayList();

           Map  map  = new HashMap();

 

        또한, J2SE1.2이상에서 Collection의 동기화가 필요한 경우에는

 

           List list = Collection.synchronizedList(new ArrayList(..));

       

        위와 같이 사용합니다.           

   

    Collection size 초기화

 

Collection default 사이즈로 만들면, 필요시 자동적으로 사이즈가 확장되나 명확히 예측이 가능한 경우에는 사이즈를 초기화 하는 편이 훨씬 효율적입니다.

 

        ) 사이즈를 지정하지 않고 Collection을 생성한 코드예

 

          List list = new ArrayList();

          HashMap map = new HashMap();

 

        ) 사이즈를 지정한 Collection 생성 코드예

           

          List list = new ArrayList(num);

          HashMap map = new HashMap(num);

 

 

    Iterator클래스보다 빠른 요소검사

 

       Collection 사이즈를 명확히 알 경우에는 Iterator클래스의 next()와 비교하여,

       Iterator클래스의 hasNext()에 의한 요소종료 체크가 필요없으며 내부처리가 간단한 List클래스의 get()메소드를  
       추천합니다
.

 

       ) Iterator클래스의  next()에 의한 요소조사

 

         Iterator iterator = array.iterator();

         while (iterator.hasNext())

         {

           Object object = iterator.next();

         }

 

       ) List클래스의 get()에 의한 요소조사

 

          int size =array.size();

          for (int i=0; i<size ; i++)

          {

            Object object = array.get(i);

          }

          

    ⑤ 요소삽입/삭제시 주의점

 

        List도중에 요소를 추가/삭제할 경우에 내부적으로 배열의 copy가 행해집니다.

따라서 요소의 수가 많으면 많을 수록 copy하는 요소수도 많아져 결과적으로 performance의 저하를 초래합니다.

내부적처리로써 [ (전체사이즈) - (삽입/삭제대상요소의 index)] 만큼의 요소가 copy되므로 아래의 예를 참조바랍니다.

 

        ) List의 맨앞에 요소를 추가/삭제하는 경우 --  속도가 느림.

 

         list.add(0, new Object());

         list.remove(0);

 

        ) List의 맨 뒤에 요소를 추가/삭제하는 경우 -- 속도가 빠름.

 

         list.add(new Object());

         list.remove(list.size() - 1);

 

 

    List요소 전체삭제

 

List요소를 전체삭제 할때, 통상 쓰는 clear()을 이용하지말고, 새롭게 List를 생성(초기화)하는 편이 효율적입니다.
왜냐하면, clear()는 내부적으로 보유하고 있는 배열의 전체요소에 null을 셋팅함으로써 전체삭제를 실현하기
때문입니다
.

 

        ) clear()에 의한 요소 전체삭제

 

          List list = new ArrayList();

         

          for(int i=0; i< num; i++) {

            list.add(new Integer(i));

          }

 

          list.clear();

 

        ) List재작성에 의한 요소 전체삭제

 

          List list = new ArrayList();

 

          for(int i=0; i< num; i++) {

            list.add(new Integer(i));

          }

 

          list = new ArrayList();

 

    ⑦ 배열요소 copy방법

    

루프를 돌며 배열요소를 하나씩 copy할 경우에는 System.arraycopy(Object src,int srcPos,Object dest,int destPos,int length)를 이용합니다메소드의 인자는 아래와 같습니다.

 

          src - the source array.

          srcPos - starting position in the source array.

          dest - the destination array.

          destPos - starting position in the destination data.

          length - the number of array elements to be copied.

       

        ) 루프를 돌며 배열소소를 copy하는 예

 

           int[] buf = new int[num];

           int[] copy = new int[num];

 

           for (int i=0; i<num; i++)

           {

              copy[i] = buf[i];

           }

       

        ) System.arraycopy()에 의한 신속한 copy

 

           int[] buf = new int[num];

           int[] copy = new int[num];

 

           System.arraycopy(buf,0, copy,0, num);

 

     List에 보존되어 있는 object 요소를 배열에 넣는 방법

 

List클래스의 toArray()를 이용하여 List에 보존되어 있는 Object요소를 배열에 넣습니다.

 

          ) 루프에 의한 object요소 copy

             

            int size = list.size();

            Integer[] result = new Integer[size];

 

            for (int i=0; i<size; i++)

            {

              result[i] = (Integer) list.get(i);

            }

 

          ) toArray()에 의한 신속한 copy

 

            int size = list.size();

            Integer[] result = new Integer[size];

 

            list.toArray(result);

 

이미지 맵

'IT Computer Utility/ETC' 카테고리의 다른 글

이전 글 다음 글