1

I've seen the HashCodeBuilder of Apache Commons Lang and the Eclipse hashCode() generation. I have to say that Eclipse's hashCode() is very ugly, but is it better to use as HashCodeBuilder in terms of performance (because an extra object creation is needed for the builder)?

I'd also like to know what you think about the equals() generation and Commons Lang's EqualsBuilder.

And if you got even better solutions, please post them too :)

3 Answers3

3

The HashCodeBuilder is much slower than just writing your own hash function. It uses reflection to iterate over each field. If you are calling this method frequently, you may see a performance hit, which may or may not be tolerable for your situation.

The hashCode function generated by eclipse uses prime numbers to help create a better hash function. Why use a prime number in hashCode? has some details on why that is

Community
  • 1
  • 1
Jeff Storey
  • 56,312
  • 72
  • 233
  • 406
  • 1
    I thought of appending each field that I want manually with the `append()` methods, not the reflection ones. Or does it not use the `hashCode()` of the appended fields and computes the hashCode by reflection? –  Jun 14 '12 at 16:07
  • 1
    If you're using the appendMethod then it looks like it does not use reflection. – Jeff Storey Jun 14 '12 at 16:53
0

HashCodeBuilder and EqualsBuilder are better compared to default methods, but if you are concerned with performance, it is better to write your own hashcode and equals method.This is because they use reflection approach.

Rule is

equal objects should produce same hashcode, equal hashcode does not imply objects are equal

Subin Sebastian
  • 10,870
  • 3
  • 37
  • 42
0

You have to choose between performance and maintainability here. The commons version will adapt itself to changes of the class, but is slower. The Eclipse generated version is fast, but it will not be updated after adding a new field, making it harder to maintain.

Bananeweizen
  • 21,797
  • 8
  • 68
  • 88