簡體   English   中英

快速靜態持久哈希表

[英]Fast Static Persisted Hash Table

我在Java中的應用程序需要一個哈希表來進行計算,並且必須在數據庫中查找數百萬個哈希表。 哈希表必須能夠非常快速地從磁盤讀取到HashTable實用程序中,並且hast表中的數據是靜態的,不需要插入或刪除。

您是否建議使用任何可用的庫?

此外,數據大小小於200MB。

如果您的數據是靜態的,為什么不使用普通的舊數組並按索引查找? 無論您打算使用什么key ,只需提供index屬性即可。 當然,如果超過最大可能的數組長度 ,則需要在多個數組之間進行分片。

我會說沒有哈希函數可以擊敗直接隨機訪問,並且在初始化期間而不是每次查找都會預先設置在您的密鑰集上分配索引的成本(“完美哈希函數”)。

如果是人類可讀的是不是一個要求,你可以喘氣訴諸只是確保您的數據實現Serializable接口,並使用ObjectOutputStream序列化的HashMap中。 這很丑陋,但它可以完成工作。

另一個選項是DataInputStream和DataOutputStream。 這些允許您讀/寫結構化二進制數據。

假設你有一個HashMap,你可以像這樣寫:

// realOutputStream should probably be a BufferedOutputStream
DataOutputStream output = new DataOutputStream( realOutputStream );
for (Map.Entry<Long, String> entry : map.entrySet()) {
    // Write the key
    output.writeLong(entry.getKey().longValue());
    byte bytes[] = entry.getBytes("UTF-8");
    // Writing the string requires writing the length and then the bytes
    output.writeInt(bytes.length);
    output.write(bytes, 0, bytes.length);
}



// realInputStream should probably be a BufferedInputStream
DataInputStream input = new DataInputStream ( realInputStream );
Map<Long, String> map = new HashMap<Long, String>();
while ( true ) {
   try {
     // read the key
     long key = output.readLong();
     // read the string length in bytes
     int strlen = output.readInt();
     // read the bytes into an array
     byte buf[] = new byte[strlen];
     output.readFully(buf, 0, strlen);
     // Create the map entry.
     map.put(Long.valueOf(key), new String(buf,"UTF-8"));
   }
   catch (EOFException e) {
     // input is exhausted
     break;
   }
}

請記住,假設您要將字符串存儲並讀取為UTF。 您可以輕松地不提供字符集並使用jvm默認編碼。 另請注意,像String這樣長度可變的東西要求您在寫入實際數據之前先寫入該數據的長度。 這樣您就可以知道需要讀入多少字節來重建該字符串。

暫無
暫無

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

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