I want to create a HashMap with RGB colors as keys. How should I store them to have best performance?
I mean, how does the “speed” of a hashmap refer to the object type of the key?
Should I use Integer (018052175) where each triplet would be one of RGB, String (1234AF) as HEX, or own Color class with int r, g, b? What might be the fastest implementation?
The speed of hash map is constrained by several essential properties of the
hashCodeandequalsfunctions:hashCodeat distributing values into buckets, andThe
hashCodefunction of aStringis very good, andStringcaches its result to improve performance. However, equality check may be longer than withInteger.The
Integerclass has a very hard-to-beat implementation ofhashCodein terms of speed, but since the hash codes of similar colors would be close to each other, you may get more collisions withIntegers.Coloris as fast as theInteger, but it is also the most descriptive. I seriously doubt that choosing one of these three representations would hamper performance so significantly as to make a visible difference, so I would suggest going for the most descriptive choice, and then profile if necessary.