我有一个相当大的HashMap(约250MB)。创建它需要大约50-55秒,所以我决定将它序列化并保存到文件中。现在从文件中读取需要大约16-17秒。
唯一的问题是这种方式似乎会使查找更慢。我一直认为HashMap是从文件中读入内存的,因此与我自己创建HashMap的情况相比,性能应该是相同的,对吧?这是我用来读取HashMap到文件中的代码:
唯一的问题是这种方式似乎会使查找更慢。我一直认为HashMap是从文件中读入内存的,因此与我自己创建HashMap的情况相比,性能应该是相同的,对吧?这是我用来读取HashMap到文件中的代码:
File file = new File("omaha.ser");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(new BufferedInputStream(f));
omahaMap = (HashMap<Long, Integer>) s.readObject();
s.close();
当我自己创建哈希表时,3亿个查找大约需要3.1秒,当我从文件中读取相同的哈希表时,需要约8.5秒。有人有想法吗?我有没有忽略什么明显的东西?
编辑:
我只是使用System.nanotime()记录时间,所以没有使用适当的基准测试方法。以下是代码:
public class HandEvaluationTest
{
public static void Test()
{
HandEvaluation.populate5Card();
HandEvaluation.populate9CardOmaha();
Card[] player1cards = {new Card("4s"), new Card("2s"), new Card("8h"), new Card("4d")};
Card[] player2cards = {new Card("As"), new Card("9s"), new Card("6c"), new Card("2h")};
Card[] player3cards = {new Card("9h"), new Card("7h"), new Card("Kc"), new Card("Kh")};
Card[] table = {new Card("2d"), new Card("2c"), new Card("3c"), new Card("5c"), new Card("4h")};
int j=0, k=0, l=0;
long startTime = System.nanoTime();
for(int p=0; p<100000000; p++) {
j = HandEvaluation.handEval9Hash(player1cards, table);
k = HandEvaluation.handEval9Hash(player2cards, table);
l = HandEvaluation.handEval9Hash(player3cards, table);
}
long estimatedTime = System.nanoTime() - startTime;
System.out.println("Time needed: " + estimatedTime*Math.pow(10,-6) + "ms");
System.out.println("Handstrength Player 1: " + j);
System.out.println("Handstrength Player 2: " + k);
System.out.println("Handstrength Player 3: " + l);
}
}
大的哈希表工作是在HandEvaluation.populate9CardOmaha()中完成的。5张牌的小型哈希表。大型哈希表的代码:
public static void populate9CardOmaha()
{
//Check if the hashmap is already there- then just read it and exit
File hashmap = new File("omaha.ser");
if(hashmap.exists())
{
try
{
File file = new File("omaha.ser");
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(new BufferedInputStream(f));
omahaMap = (HashMap<Long, Integer>) s.readObject();
s.close();
}
catch(IOException ioex) {ioex.printStackTrace();}
catch(ClassNotFoundException cnfex)
{
System.out.println("Class not found");
cnfex.printStackTrace();
return;
}
return;
}
// if it's not there, populate it yourself
... Code for populating hashmap ...
// and then save it to file
(
try
{
File file = new File("omaha.ser");
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(new BufferedOutputStream(f));
s.writeObject(omahaMap);
s.close();
}
catch(IOException ioex) {ioex.printStackTrace();}
}
当我自己填写内容时(即文件不存在),HandEvaluationTest.Test() 中的查找需要8秒而不是3秒。也许这只是我非常幼稚的测量时间流逝的方式?