Don't use parametereized constructor in Grails for domain objects. This is slower than empty constructor.
This performance issue become significant when creating large number of domain objects in loop.
Showing posts with label groovy. Show all posts
Showing posts with label groovy. Show all posts
Monday, February 6, 2012
Wednesday, February 1, 2012
Overriding equals in Groovy
I was overriding equals method in for a Groovy class and got into StackOverflow error.
I was getting stackoverflow at line: if (this == obj). Groovy's equals calls the equals method instead of comparing the reference.
I fixed it using bellow syntax: if (this.is(obj)). The corrected code looks like:
class ObjKey {
long id
String value
public boolean equals(Object obj) {
if (!(obj instanceof ObjKey)) {
return false;
}
if (this == obj) {
return true;
}
ObjKey rhs = (ObjKey) obj;
return new EqualsBuilder()
.append(id, rhs?.id)
.append(value, rhs?.value)
.isEquals();
}
public int hashCode() {
return new HashCodeBuilder()
.append(id)
.append(value)
.toHashCode();
}
}
I was getting stackoverflow at line: if (this == obj). Groovy's equals calls the equals method instead of comparing the reference.
I fixed it using bellow syntax: if (this.is(obj)). The corrected code looks like:
class ObjKey {
long id
String value
public boolean equals(Object obj) {
if (!(obj instanceof ObjKey)) {
return false;
}
if (this.is(obj)) {
return true;
}
ObjKey rhs = (ObjKey) obj;
return new EqualsBuilder()
.append(id, rhs?.id)
.append(value, rhs?.value)
.isEquals();
}
public int hashCode() {
return new HashCodeBuilder()
.append(id)
.append(value)
.toHashCode();
}
}
Subscribe to:
Posts (Atom)