If we have a HashMap<String,String> H, and we use the code H.put("Hello","World").
Would the time complexity be the same as in the case where we use an integer key-value pair in a HashMap? I feel that the performance with String should be poorer, as hashing the String would be an O(String length) operation.
Add a comment
|
1 Answer
Yes, It's performance will be poorer since hashing a string is indeed slower then hashing an integer.
In fact, Java uses a specific formula for hashCode() of String, which you can see here, and it does check all the charachters of the string, as you would expect.
In my Eclipse the code for hashCode():
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
But why are you comparing these two things? It doesn't make much sense to compare complexity of two algorithms which do different things.
2 Comments
Dhruv Mullick
I didn't mean to compare, I was wondering if there is any drop in performance due to the length of string.
Yossi Vainshtein
Yes. You can even see the code for
String.hashCode() in your eclipse and see the loop. (see edit in my answer)