2013년 6월 11일 화요일

Android SparseArray

이전 블로그에서 이전 함 (원본 글 2013/06/11 작성)

일반적으로 사용하는 자료구조 중 하나가
Map<Integer, String> 인데 data collision으로 인한 성능 문제로
Android에서는 SparseArray를 추천하고 있다.
하지만 Java Collection Interface를 지원하지는 않는데... 왜?!

[SparseArray]

 public classSparseArrayextends Objectimplements Cloneable
java.lang.Object
   ↳android.util.SparseArray<E>


[HashMap, SparseArray 사용]

별 차이는 없음.
 Old code with HashMap
 Map<Integer, Bitmap> _bitmapCache = new HashMap<Integer, Bitmap>();
   private void fillBitmapCache() {
        _bitmapCache.put(R.drawable.icon, BitmapFactory.decodeResource(getResources(), R.drawable.icon));
        _bitmapCache.put(R.drawable.abstrakt, BitmapFactory.decodeResource(getResources(), R.drawable.abstrakt));
        _bitmapCache.put(R.drawable.wallpaper, BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper));
        _bitmapCache.put(R.drawable.scissors, BitmapFactory.decodeResource(getResources(), 
    }
 
Bitmap bm = _bitmapCache.get(R.drawable.icon);
New code with SparseArray
 SparseArray<Bitmap> _bitmapCache = new SparseArray<Bitmap>();
   private void fillBitmapCache() {
        _bitmapCache.put(R.drawable.icon, BitmapFactory.decodeResource(getResources(), R.drawable.icon));
        _bitmapCache.put(R.drawable.abstrakt, BitmapFactory.decodeResource(getResources(), R.drawable.abstrakt));
        _bitmapCache.put(R.drawable.wallpaper, BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper));
        _bitmapCache.put(R.drawable.scissors, BitmapFactory.decodeResource(getResources(), 
    }
 
Bitmap bm = _bitmapCache.get(R.drawable.icon);



[SparseArray iteration]
Collection interface 미지원으로 이렇게 loop을 사용해야 한다.. 귀찮아..

up vote83down voteaccepted
seems I found the solution. I havent properly noticed keyAt(index) function.
So I'll go with something like this
int key = 0;
for(int i = 0; i < sparseArray.size(); i++) {
   key = sparseArray.keyAt(i);
   // get the object by the key.
   Object obj = sparseArray.get(key);
}
share|improve this answer


[Map, HashMap 그리고 SparseArray 설명]


[ParseArray Versus Hashmap 성능 비교]

 Results SparseArray Results
The SparseArray is a very quick data structure for sizes of 10,000 and less. If you are pulling data from your array considerably more than adding to it, you can get away with a size of 100,000. It starts to slow down a bit with the jump to 1,000, but nothing too surprising.
 Hashmap Results





댓글 없음:

댓글 쓰기