[SOLVED] Cache resolved ASTNode binding in comparator? [message #650109] |
Fri, 21 January 2011 18:44 |
|
Hi,
I'm not sure resolving binding in the compare implementation of a comparator is a best practice. The same binding is resolved several times.
I'm thinking of caching the binding for each compare session (Collections.sort(...)). Does anyone already do it?
What would be the best key to use from an ASTNode instance?
Thanks,
Chris
[Updated on: Thu, 27 January 2011 08:15] Report message to a moderator
|
|
|
|
Re: Cache resolved ASTNode binding in comparator? [message #650180 is a reply to message #650161] |
Sat, 22 January 2011 15:06 |
|
Hi Deepak,
Here is a code snippet of a comparator which sort catch blocks by exception hierarchy or alphabetically when exceptions are not related.
Then, I'm not so sure the API below is safe. Could you tell me more about it? When cache should be reset?
CatchClauseComparator.getBinding(Type): ITypeBinding
Thank you,
Chris
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jdt.core.dom.CatchClause;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.Type;
public final class CatchClauseComparator implements Comparator<CatchClause> {
private final Map<Integer, ITypeBinding> _bindings = new HashMap<Integer, ITypeBinding>();
@Override
public int compare(final CatchClause o1, final CatchClause o2) {
final ITypeBinding exceptionType1 = this.getBinding(o1.getException().getType());
final ITypeBinding exceptionType2 = this.getBinding(o2.getException().getType());
int rval = 0;
if (CatchClauseComparator.isSubType(exceptionType1, exceptionType2)) {
rval = Integer.MIN_VALUE;
} else if (CatchClauseComparator.isSubType(exceptionType2, exceptionType1)) {
rval = Integer.MAX_VALUE;
} else {
rval = exceptionType1.getJavaElement().getElementName().compareTo(exceptionType2.getJavaElement().getElementName());
}
return rval;
}
private ITypeBinding getBinding(final Type type) {
ITypeBinding binding = this._bindings.get(type.hashCode());
if (binding == null) {
binding = type.resolveBinding();
this._bindings.put(type.hashCode(), binding);
}
return binding;
}
private static boolean isSubType(final ITypeBinding type1, final ITypeBinding type2) {
boolean isSubType = false;
ITypeBinding superClass = type1.getSuperclass();
while ((superClass != null) && !isSubType) {
if (superClass.equals(type2)) {
isSubType = true;
} else {
superClass = superClass.getSuperclass();
}
}
return isSubType;
}
}
|
|
|
|
|
|
|
Powered by
FUDForum. Page generated in 0.04550 seconds