Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory efficiency with HashMap in Android

When I first started learning about HashMap's I wrote my companies in-house Android app with individual maps for each line item's properties. Line items are dynamic and have several properties with corresponding values.

Example (Not all Maps are included):

// Preceding onCreate()
HashMap<Integer, Double> latMap;
HashMap<Integer, Double> lngMap;
HashMap<Integer, String> descMap;
// In onCreate()
latMap = new HashMap<Integer, Double>();
lngMap = new HashMap<Integer, Double>();
descMap = new HashMap<Integer, String>();

LogCat (Structure: {ItemNumber=Value, ItemNumber=Value}):

-- latMap output --
{1=0.0, 2=0.0}
-- lngMap output --
{1=0.0, 2=0.0}
-- descMap output --
{1=NULL, 2=NULL}

Now I am testing only having 2 maps, the main HashMap contains the item numbers and a containing map which holds individual properties and values

Example:

// Preceding onCreate()
HashMap<Integer, HashMap<String, String>> testMapFull;
HashMap<String, String> testMapContent;
// In onCreate()
testMapFull = new HashMap<Integer, HashMap<String, String>>();
testMapContent = new HashMap<String, String>();

LogCat (Structure: {ItemNumber{Property=Value, Property=Value}}):

{
    1={
        object_lat=0.0,
        object_lng=0.0,
        desc=NULL,
    },
    2={
        object_lat=0.0,
        object_lng=0.0,
        desc=NULL,
    }
}

My question: Is there a significant difference in memory efficiency, etc? Everything is currently working as is. And yes, I know that the 2 maps have to be better then several, but they would contain the same amount of information with less to instantiate.

like image 354
jnthnjns Avatar asked Apr 20 '26 12:04

jnthnjns


1 Answers

Why can't you declare a custom class that will hold the whole information about the particular item? It will allow you to reduce the HashMap's number to 1.

public class Item {
    public double lat;
    public double lng;

    public String desc;
}

HashMap<Integer, Item> itemMap;

It requires much less memory because uses only one HashMap and allows to avoid Boxing/Unboxing operations that create unnecessary temporary objects.

Also you can reduce the number of Boxing/Unboxing operations even more by using SparseArray instead of HashMap<Integer, ?>

like image 90
Vladimir Mironov Avatar answered Apr 23 '26 02:04

Vladimir Mironov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!