Does anybody have any idea about how I could improve the performance of this method? Note that this.allActions is a hashmap with around half a million keys.
Maybe there is a faster way of iterating through a HashMap that I don't know.
public String get_random_legal_action(String stateJSON) {
Collections.shuffle(this.allActionsKeys);
boolean legal;
HashMap<String, Integer> state = new Gson().fromJson(stateJSON, this.stateType);
for (String action : this.allActionsKeys) {
legal = true;
for (Map.Entry<String, Integer> precondition : this.allActions.get(action).precondition.entrySet()) {
try {
if (!state.get(precondition.getKey()).equals(precondition.getValue())) {
legal = false;
break;
}
} catch (NullPointerException e) {
if (!this.immutableProps.contains(precondition.getKey())) {
legal = false;
break;
}
}
}
if (legal)
return action;
}
return null;
}
Convert the HashMap
to LinkedHashMap
to improve the performance,
the complexity of Get O(1), Contains O(1) and Next O(1)
, You can create custom Key class and update hashCode()
function
Use it in like LinkedHashMap<Key, Integer>
static class Key {
private static final int R = 256;
private static final long Q = longRandomPrime();
private String k;
public Key(String k) {
this.k = k;
}
public String key() {
return k;
}
@Override
public int hashCode() {
return Long.hashCode(hash());
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null)
return false;
if (getClass() != o.getClass())
return false;
Key other = (Key) o;
return k.equals(other.k);
}
@Override
public String toString() {
return k;
}
private long hash() {
long h = 0;
for (int j = 0; j < k.length(); j++) {
h = (R * h + k.charAt(j)) % Q;
}
return h;
}
private static long longRandomPrime() {
BigInteger prime = BigInteger.probablePrime(31, new Random());
return prime.longValue();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.