Thursday, May 31, 2012

How to juice your java performance

Warning: This is a preoptimization

In my previous post about equals and hashcode I thought I'd point out how to redesign the class in question to make better use of performance. If you have a situation where you create groups of objects that are immutable, but you need to pass them around in hashsets and/or look things up, a way to increase performance is to change from something like the following:

package blog.mainguy;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

public class LookupEntity {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public boolean equals(Object other) {
        if (other != null && other instanceof LookupEntity) {
            return new EqualsBuilder().append(this.getName(), ((LookupEntity) other).getName()).isEquals();
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17,31).append(this.getName()).hashCode();
    }
}

to something like
package blog.mainguy;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

public class LookupEntity {
    private String name;
    private LookupEntity() {
    }
    public LookupEntity(String name) {
        
        this.name = name == null?"":name;
        hashCode = name.hashCode();
    }
    public String getName() {
        return name;
    }
    private int hashCode;

    @Override
    public boolean equals(Object other) {
       if (other != null && other instanceof LookupEntity) {
            return this.name.equals(((LookupEntity)other).getName())
        }
    }

    @Override
    public int hashCode() {
        return hashCode;
    }
}

Note, I have not profiled this, it is based on my perception and understanding of how java works. It is also (as I noted) a pre-optimization that I personally wouldn't necessarily start with (though in many cases I might).

2 comments:

Anonymous said...

If you want to use your entity in HashSets, making it really immutable (taking out the setName() is a minimum fix to the first version, if you want to avoid errors casued from someone using the set method on a set/map member.

Mike Mainguy said...

Oh shoot, good point, thanks!