java - 如何通过 Java 中的 HashMap 提高迭代性能?
问题描述
有人知道如何提高这种方法的性能吗?请注意,this.allActions 是一个带有大约一百万个键的哈希图。
也许有一种更快的方法来遍历我不知道的 HashMap。
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;
}
解决方案
转换HashMap
为LinkedHashMap
以提高性能,
Get O(1) 的复杂度,包含 O(1) 和 Next O(1)
, 您可以创建自定义 Key 类和更新hashCode()
函数
像这样使用它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();
}
}
推荐阅读
- c - 《Head First C》一书demo中关于strstr()和fgets()的问题
- amazon-web-services - boto3 filter_log_events 不返回 cloudwatch 日志
- java - 如何通过使用 testng 设置优先级在多个类中一个一个地运行所有方法
- php - 钩子 pre_controller 中的 Codeigniter 访问会话
- php - MySQL Workbench 与 PHP 的性能不同
- javascript - React.createElement:类型无效(地图)
- python - 仅 50% 的 RandomForestClassifier 用于好坏电影评论的情感分析
- bash - 如何在 bash 的新选项卡中打开子 shell,以便同时运行父 shell 和子 shell?
- android - 启动 Dagger2,如何构建结构?
- google-cloud-platform - 尝试使用 Cloud Shell 连接到 Cloud SQL 实例时出错