我正在使用一个内部类,它是 HashMap 的子类。我有一个String
作为键和double[]
值。我每个存储大约 200 个双打double[]
。我应该使用大约 700 MB 来存储键、指针和双精度。但是,内存分析表明我需要的远不止这些(略超过 2 GB)。
使用TIJmp(分析工具)我看到有一个char[]
几乎使用了总内存的一半。TIJmp 说char[]
来自Serializable
and Cloneable
。其中的值范围从字体列表和默认路径到消息和单个字符。
Serializable
JVM中的确切行为是什么?因此,它是否始终保持“持久”副本,从而使我的内存占用量增加一倍?如何在运行时编写对象的二进制副本而不将 JVM 变成内存占用者?
PS:内存消耗增加最多的方法是下面的一种。该文件有大约 229,000 行,每行 202 个字段。
public void readThetas(String filename) throws Exception
{
long t1 = System.currentTimeMillis();
documents = new HashMapX<String,double[]>(); //Document names to indices.
Scanner s = new Scanner(new File(filename));
int docIndex = 0;
if (s.hasNextLine())
System.out.println(s.nextLine()); // Consume useless first line :)
while(s.hasNextLine())
{
String[] fields = s.nextLine().split("\\s+");
String docName = fields[1];
numTopics = fields.length/2-1;
double[] thetas = new double[numTopics];
for (int i=2;i<numTopics;i=i+2)
thetas[Integer.valueOf(fields[i].trim())] = Double.valueOf(fields[i+1].trim());
documents.put(docName,thetas);
docIndex++;
if (docIndex%10000==0)
System.out.print("*"); //progress bar ;)
}
s.close();
long t2 = System.currentTimeMillis();
System.out.println("\nRead file in "+ (t2-t1) +" ms");
}
哦!,HashMapX 是一个内部类,声明如下:
public static class HashMapX< K, V> extends HashMap<K,V> {
public V get(Object key, V altVal) {
if (this.containsKey(key))
return this.get(key);
else
return altVal;
}
}