Skip to content

Instantly share code, notes, and snippets.

@ahgittin
Created December 8, 2011 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahgittin/1445672 to your computer and use it in GitHub Desktop.
Save ahgittin/1445672 to your computer and use it in GitHub Desktop.
reflective equals timing test
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
public class ReflectiveEquals {
static class Fast {
public int a = 1;
public int b = 2;
public String c = "foo";
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
Fast other = (Fast) obj;
if (a != other.a)
return false;
if (b != other.b)
return false;
if (c == null) {
if (other.c != null)
return false;
} else if (!c.equals(other.c))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + a;
result = prime * result + b;
result = prime * result + ((c == null) ? 0 : c.hashCode());
return result;
}
}
static class Slow extends Fast {
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
private static long startTime;
static void reset() {
startTime = System.nanoTime();
}
static void done(String name) {
long elapsedTime = System.nanoTime() - startTime;
System.out.println(name+": "+(1.0d*elapsedTime/N));
reset();
}
static int N=1000*1000, n=5;
public static void main(String[] args) {
Fast f = new Fast();
Slow s = new Slow();
for (int i=0; i<n; i++) {
reset();
for (int j=0; j<N; j++) {
f.equals(s);
}
done("equals fast");
for (int j=0; j<N; j++) {
s.equals(f);
}
done("equals slow");
for (int j=0; j<N; j++) {
f.hashCode();
}
done("hashCo fast");
for (int j=0; j<N; j++) {
s.hashCode();
}
done("hashCo slow");
}
System.out.println(f.equals(s)+" "+s.equals(f)+" "+f.hashCode()+" "+s.hashCode());
}
/*
N = 1 million
equals fast: 8.24
equals slow: 1207.192
hashCo fast: 11.928
hashCo slow: 1759.674
equals fast: 29.136
equals slow: 645.907
hashCo fast: 0.806
hashCo slow: 1567.595
equals fast: 2.772
equals slow: 623.905
hashCo fast: 0.754
hashCo slow: 1605.038
equals fast: 2.73
equals slow: 620.861
hashCo fast: 0.801
hashCo slow: 1533.06
equals fast: 2.701
equals slow: 617.333
hashCo fast: 0.835
hashCo slow: 1589.757
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment