I have a bunch of Thingy
objects that I'm keeping track of using long
ID numbers. Since I have no guarantees about ID sequence, I'm keeping them in a HashMap<Long, Thingy>
for random access. However, in Android, they have this very nice class called SparseArray
which they claim is faster than my HashMap
for how I'm using it. Perhaps most notably, it doesn't have the autoboxing tax. Unfortunately, the keys are int
, not long
.
The values of my long
IDs are such that I'm not worried about overflowing the range of int
anytime this century. Is that casting from long
to int
plus SparseArray
optimizations are going to be cheaper than autoboxing long
to Long
for my HashMap
operations? My intuition says yes, but I'd like some additional input.
Um. Casting long
to int
will probably be faster, yes, but it's not clear whether or not it will be correct.
Casting long
to int
will be definitely faster, as it is just one JVM command (l2i) opposing to memory allocation and new object creation when using boxing, but, as Louis pointed, you are losing precision. If you're sure that your id values are in int
range, you probably safe, but I would not go with such assumptions.
What I would do is to investigate possibility to copy that SparseArray class from Android sources and modify it to use long
keys. I am currently looking at it and at a first glance that is definitely possible.