Re: HashMap with primitive int key



Andrew E wrote:

CustomerOrder o = index.get(123)

Perhaps it is my C++ background, but the idea of allocating an object for every
ID when I can just use an int bothers me.

The overhead for allocating a small object is actually very small. It shouldn't come as a surprise that Java runtimes are heavily optimised for allocating small, short-lived objects. I get around 30-40 cycles on my PII. Can be as low as 10 instructions on some architectures.


You've actually picked a number in an interesting range. Integer.valueOf (which autoboxing uses) always returns the same value for at least those integers in [-128, 127]. Years ago when I was dealing with an applet which generated lots of small Integers, I used an array of the first 256 to deal with the almost always small IDs. If nothing else it cleared some mess off the profiler.

If you are dealing with large numbers but often repeating the same values there is a cunning thread-safe trick that works from 1.5:

http://jroller.com/page/tackline?entry=fast_immutables

(Note comments.)

Has anyone out there already written a modified hashmap class that uses int as
the key?

IIRC there is a Apache Jakarta Commons Primitives subsubsubproject for primitive collections. But I suggest that you first visit Mr OptimizeIT, Mr JProbe or one of their friends before adding dependencies and obscurities. ;)


Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/
.