eclipse-collections icon indicating copy to clipboard operation
eclipse-collections copied to clipboard

Create immutable primitive collection wrappers which cache the hashcode.

Open vijay-daniel opened this issue 9 years ago • 5 comments

For immutable primitive collections, it makes sense to cache the hash code once it is calculated. Currently, it is recalculated everytime.

A similar strategy to the one in java.lang.String#hashCode can be used.

vijay-daniel avatar Jul 29 '16 19:07 vijay-daniel

Thanks for the interesting proposal! Your suggestion makes sense to me.

Would you be interested in contributing to this issue? We are happy to accept contributions. Please let us know.

itohro avatar Aug 01 '16 01:08 itohro

It's not always advantageous to cache the hash code. Consider an immutable singleton set containing a String. Caching the hash code would increase memory usage and not have a material impact on speed since the String already caches the hash code. And the speed of a collection's hash code calculation only matters if it's stored in another hash table. How common is that?

An alternative would be to add wrappers that cache the hash code. The wrapper would implement an immutable interface like ImmutableSet, delegate all methods except hashCode, and cache the hash code.

motlin avatar Aug 01 '16 01:08 motlin

@motlin , my understanding is that this proposal is only for immutable "primitive" collections, so strictly speaking, your counter argument might not be relevant.

Though you made the valid point that adding cache increase memory consumption, especially for fixed size collections. Also it might not be too common to care about the hash speed for collections.

The suggestion to add wrappers helps users to choose better hash speed containers only when they need, so I agree with that approach if we were to implement this.

itohro avatar Aug 01 '16 02:08 itohro

Adding a wrapper gives clients the flexibility to choose to have the overhead of maintaining a cached hash code (however, minimal). I agree.

@itohro I'll pick this up and raise a pull request in the coming week.

@motlin The actual use case was to use a byte array as a key, and avoid the retrofitting of ByteBuffer. But you're right. It is not really a common use case.

vijay-daniel avatar Aug 03 '16 06:08 vijay-daniel

@vijay-daniel Are you still interested in contributing this or should I close the issue?

donraab avatar Apr 01 '20 23:04 donraab