Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap Alternatives for Android Application

I am having OOM issues with java.util HashMap so I am looking for memory friendly HashMap alternatives to standard Java Hashmap. I tried Trove and it improved a little but still ends up with OOM from time to time. I can accommodate some speed loss if memory is efficient.

I am not looking for a DB. File-based HashMap implementations are also fine as long as they are working offline. I am storing primitives like int and byte.

Also, please indicate if you had any experience and how much improvement you had in terms of memory.

like image 571
Erol Avatar asked Jan 16 '23 12:01

Erol


2 Answers

I can think of two options that would work for you -- which is the best entirely depends on your application. The first is to use WeakReference or SoftReference. Now keep in mind that as of Android 2.3 the VM has become much more agressive so collecting VM may collect these type of references more frequently. Personally, I'm not a huge fan of using these type of references for this sole reason but some individuals might argue differently. The second option, and the one which I would recommend, is to look in to an LRU cache. You can implement your own LRU cache using a LinkedHashMap. But if you are using your map for storing Bitmaps I would strongly suggest you have a look at the Bitmap Cache provided by the Android compatibility package which includes a bitmap cache. Here's a few links you can use to read up on:

Weak References

Soft References

LRU Cache using LinkedHashMap

Android Bitmap Cache and why you should avoid Weak/Soft References

like image 190
jagsaund Avatar answered Jan 20 '23 02:01

jagsaund


You should have a look at ArrayMap and SparseArray. These are the memory efficient alternatives to using HashMap in android.

like image 29
Nishant Srivastava Avatar answered Jan 20 '23 04:01

Nishant Srivastava