【发布时间】:2012-05-24 22:57:51
【问题描述】:
我尝试使用文件内容构建地图,我的代码如下:
System.out.println("begin to build the sns map....");
String basePath = PropertyReader.getProp("oldbasepath");
String pathname = basePath + "\\user_sns.txt";
FileReader fr;
Map<Integer, List<Integer>> snsMap =
new HashMap<Integer, List<Integer>>(2000000);
try {
fr = new FileReader(pathname);
BufferedReader br = new BufferedReader(fr);
String line;
int i = 1;
while ((line = br.readLine()) != null) {
System.out.println("line number: " + i);
i++;
String[] strs = line.split("\t");
int key = Integer.parseInt(strs[0]);
int value = Integer.parseInt(strs[1]);
List<Integer> list = snsMap.get(key);
//if the follower is not in the map
if(snsMap.get(key) == null)
list = new LinkedList<Integer>();
list.add(value);
snsMap.put(key, list);
System.out.println("map size: " + snsMap.size());
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("finish building the sns map....");
return snsMap;
程序一开始非常快,但当打印的信息是:
map size: 1138338
line number: 30923602
map size: 1138338
line number: 30923603
....
我尝试用两个 System.out.println() 子句来判断 BufferedReader 和 HashMap 的性能,而不是 Java 分析器。 有时获取行号信息后需要一段时间才能获取地图大小的信息,有时获取地图大小后需要一段时间才能获取行号信息的信息。我的问题是:这让我的程序变慢了?大文件的 BufferedReader 或大地图的 HashMap?
【问题讨论】:
-
为什么要打两次电话
get?不要将现有列表放到地图上。 -
使用分析器,您不必猜测什么是慢什么是快...
-
从 while 循环中删除 System.out.println 并重试。
-
地图中有超过 110 万个 LinkedList。内存不足了吗?
-
我对这个问题投了反对票,因为它不能用给出的信息客观地回答,正如所有答案中的推测所证明的那样。为了有效地查明 Java 性能问题,使用分析器(或类似分析器,如线程转储)是迄今为止最好的方法。
标签: java hashmap bufferedreader