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 hashCode
and equals
functions:
- How easy it is to calculate,
- How well is
hashCode
at distributing values into buckets, and
- How easy it is to compare values for equality
The hashCode
function of a String
is very good, and String
caches its result to improve performance. However, equality check may be longer than with Integer
.
The Integer
class has a very hard-to-beat implementation of hashCode
in terms of speed, but since the hash codes of similar colors would be close to each other, you may get more collisions with Integer
s.
Color
is as fast as the Integer
, 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.
The only difference is going to be the speed of the hashcode/equals functions, and an Integer should be the fastest, though it is unlikely to be a bottleneck in any case. You should probably use whatever is going to be most convenient elsewhere in the code.
HashMap
is based on hashCode()
and Integer.hashCode()
is as fast as you can get (it's an identity function):
a hash code value for this object, equal to the primitive int
value represented by this Integer
object.
Thus go for Integer
representing 24-bit RGB value. However it turns out Color.hashCode()
is as fast, and since Color
class is much more expressive and readable than Integer
, use Color
class instead.
Java has a built in class for storing color called Color.
I would go and make optimizations (using integer will not be much faster I guess) unless you actually see its a bottleneck
Use Integer
s, and get them with new Color(r, g, b).getRGB()
.
To get the color from an integer, just use new Color(hashmap.get(index))
.
Integer.hashCode()
is no faster than Color.hashCode()
. java.awt.Color
's hashCode
implementation (Java 1.6):
/**
* Computes the hash code for this <code>Color</code>.
* @return a hash code value for this object.
* @since JDK1.0
*/
public int hashCode() {
return value;
}
equals
for both are also equivalent. So in your case I'd use Color
as it better conveys the semantics.