簡體   English   中英

使用兩個包含相似值的 HashMap 保留 memory

[英]Preserving memory with two HashMaps that contain similar values

我將 2 個大型數據集依次加載到兩個單獨的 HashMap 中。 (數據集被序列化為許多 Record 對象,如下所示)。 HashMap 是這樣表示的,鍵是 Record 的 id:

Map<Long, Record> recordMapA = new HashMap<>();
Map<Long, Record> recordMapB = new HashMap<>();

記錄 object 如下所示:

class Record {
  Long id; 
  Long timestamp; 
  String category;
  String location;  
}    

在許多情況下,兩個數據集之間的記錄是相同的,只是時間戳字段不同。 對於我的用例,如果除時間戳字段之外的所有字段值都相同,則任何兩個 Record 對象都相等。

// These two records are the same because only the timestamp differs
Record recordA = new Record(54321, 1615270861975L, "foo", "USA"); 
Record recordB = new Record(54321, 1615357219994L, "foo", "USA"); 

To preserve memory, is there a way to make it so that if two Record objects are "equal", both of those map entry values in maps A and B would refer to the same Record object in memory? 我已經覆蓋了 Record object 的 equals 和 hashCode 方法以忽略時間戳,然后檢查 RecordMapA 是否已經包含相同的記錄。 如果是這樣,我將 RecordMapA 中的記錄放入 RecordMapB 中,而不是將已從數據集 B 序列化的新 Record 放入 Map B 中。但是到目前為止,對 memory 的影響似乎可以忽略不計。

附帶說明的是,我需要保留兩張地圖(而不是將它們合並為一張)以便以后進行比較。

如果記錄“足夠小”,那么我不會費心去嘗試任何花哨的東西。 對於大型記錄,最簡單的方法似乎是做你正在做的事情。

void addToMap(Long key, Record rec, Map<Long,Record> map, 
              Map<Long,Record> otherMap) {
    Record existing = otherMap.get(key);
    map.put(key, existing != null ? existing : rec);
]

假設如果鍵存在,則該鍵定位的記錄必須相同。 如果不是這種情況,您需要檢查。

void addToMap(Long key, Record rec, Map<Long,Record> map, 
              Map<Long,Record> otherMap) {
    Record existing = otherMap.get(key);
    if (existing != null && existing.equals(rec))
         map.put(key, existing);
    else
         map.put(key, rec);
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM