Reputation: 527
I am translating 16-bit codes from a legacy device into strings as defined by a table. There are over 2,000 codes, and the codes are not consecutive.
They are currently defined in a HashMap like this...
public class SomeActivity {
private static final Map<Integer, String> myMap;
static {
Map<Integer, String> aMap = ...;
aMap.put(0x2345, "this");
aMap.put(0xFEA3, "that");
...
myMap = Collections.unmodifiableMap(aMap);
}
}
This is being ported for android, and I am concerned about how much RAM this will use up on a device. Can I do something similar, but stored in program memory?
Upvotes: 0
Views: 698
Reputation: 39403
A SparseArray
(http://developer.android.com/reference/android/util/SparseArray.html) would be more suitable than a basic HashMap.
You could also put that in a Property file (see http://developer.android.com/reference/java/util/Properties.html) that you put in the assets of your program (you still have to load all the file in memory to read 1 value)
You can even pre-make an sqlite database out of it and copy it from your assets (see http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/). In this case, the values are in file, and only required elements are loaded.
However, I wouldn't worry about 2000 items in RAM unless your strings are very long.
Upvotes: 1
Reputation: 48884
The codes may not be consecutive, but if they're fairly dense (i.e. the likelihood a number between min(keys)
and max(keys)
exists is high, say over 75%) you might be able to save some space by pre-constructing a String[]
object of size max(keys)-min(keys)
and using it like a map.
If it's available / an option for Android development, another excellent alternative for primitive maps and other data structures is the Trove library which can similarly save you a lot of space and time when working with primitive data structures.
Alternatively, since you call Collections.unmodifiableMap()
consider Guava's ImmutableMap
- it's not as efficient as Trove, which avoids auto-boxing primitives, but it is more memory efficient than Java's standard HashMap (though slightly slower).
That said, like the comments suggest, you may very well be worrying about nothing. As always, "Premature optimization is the root of all evil." It's quite likely a simple Java HashMap will serve you just fine.
Upvotes: 2