Java – which length is the string key of a HashMap that is considered a bad habit?

I always pay attention to good performance and clean code

I tried to grasp whether it was reasonable to have a HashMap with a 150 character key

>Is there any law on the length of HashMap keys? > Using string keys can be said to be 150 characters. Is this considered a bad habit? > Does it affect performance? At what length?

Solution

Not really. A 150 character string is a relatively trivial calculation of a hashcode

Having said that, in this case, I suggest you test it!

Create a routine to fill the HashMap. For example, insert a size representing the random value of the usage scene, in which 5 strings are used as keys Measure how long it takes, then do the same for the 15 character keys to see how it scales

In addition, strings in Java are immutable, which means that hashcode can be cached for each string stored in the string constant pool, and there is no need to recalculate when calling hashcode on the same string object

This means that although you calculate a large hash code when creating a map, many of them have been pre calculated and cached when accessing, making the size of the original string more irrelevant

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>