提高阅读效率

Increase the performance of reading

我正在阅读各种文件,每个文件包含大约 10,000,000 行。前几个文件读取速度很快,但在大约第 7 个文件时性能下降。事实上,它是如此低效,我不得不使用 -XX:-UseGCOverheadLimit

HashMap<String,String> hm = new HashMap();
File dir2 = new File(direc);
File[] directoryListing2= null;

   directoryListing2 = dir2.listFiles();

  if (directoryListing2 != null) {

    for (File child2 : directoryListing2) {
        BufferedReader br2= null;   

        br2 = new BufferedReader(new FileReader(child2));

        String line2=null;

            while ((line2 = br2.readLine()) != null) {
                if(!(line2.isEmpty())){


                    JSONObject thedata = new JSONObject(line2);

                         String name = (String)thedata.get("name");
                         String surname = (String)thedata.get("surname");
                         hm.put(name, surname);

                     }
                }
            br2.close();

            }

    }

为什么性能会下降这么多,我怎样才能让它更有效率?

您要在地图中插入 1000 万个条目 - 每个条目至少使用 28 个字节(假设姓氏只有一个字符),如果姓氏更长,则更多。

28 是一个粗略的估计:每个字符串指针 4 个字节 = 8 个字节,1 个字符串需要 16 个字节,映射中条目的引用需要 4 个字节 - 它可能需要更多但给出了一个顺序规模

所以每个文件读取至少使用 280MB 的堆。你做了 7 次 => 2GB。那是假设所有的值都是一个字符长——我想它们不是。

您需要有一个足够大的最大堆大小,否则代码会给垃圾收集器带来很大压力,并且可能 运行 内存不足。

如评论中所述,您还可以预先调整地图的大小以避免过多的重新散列。