In Java, what's the most performant (time, memory) way to map longs to objects?
I'm storing a (possibly large) number of objects in memory that I want to refer to by long
identifiers. Currently, I'm using a standard HashMap<Long, MyClass>
. I was wondering if there might be a better way to do it, since intuitively, I'd think that wrapping long
in a Long
doesn't really make sense.
Note that, as of now, this question is still somewhat academic, so far, I haven't any performance problems with the current solution. It may well be that it never even becomes one. Soon, however, I expect substantial growth in the data I need to process, and I'm starting to开发者_如何学Python compile a list of ideas at what I might want to take a look if things get slow.
First of all, I really doubt this should be necessary. But if it does, take a look at TLongObjectHashMap in trove4j. That does exactly that :)
For the record, it does not wrap a hashmap but uses arrays to store state.
There's also some benchmarks on the trove site, that may help.
I'd be very surprised if the Maps provided by Java would not be sufficient for your needs. If your data set grows so large that memory would be a problem it would make a lot more sense to look into using a database.
You could write your own HashMap implementation using a primitive long for the key instead of a Long wrapper. Its not hard to cut and paste the JDK HashMap to do this.
You can leave this until you need it as the refactor should be simple. Java's autoboxing will make it possible to just drop in your new class. Call to java.util.HashMap with a primitive long will now work without being boxed. You will need to change code that expects an null for the missing key case to check for a zero instead.
精彩评论