Is casting long to int cheaper than autoboxing long to Long?

Go To StackoverFlow.com

1

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.

2012-04-04 20:47
by Argyle
This had been asked here. See http://stackoverflow.com/questions/3430671/performance-impact-of-autoboxin - TechTrip 2012-04-04 20:57


3

Um. Casting long to int will probably be faster, yes, but it's not clear whether or not it will be correct.

2012-04-04 20:51
by Louis Wasserman
The correctness thing is unlikely rear its head, but I'm certainly aware of the possibility. Changing the ID type will impact a lot of places, though. Bleh. I guess I'll leave it alone for now. It works well enough - Argyle 2012-04-04 21:06


1

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.

2012-04-04 21:14
by uaraven
The thought had occurred to me - Argyle 2012-04-04 21:16
Ads