对许多文件循环使用 MD5 计算器时出现性能问题

Ita*_*Hay 3 java performance md5

我正在创建一个程序,通过将文件的 MD5 与已检查的 MD5 的数据库进行比较来检查文件。

它循环访问数千个文件,我发现它使用了大量内存。

如何使我的代码尽可能高效?

    for (File f : directory.listFiles()) {


        String MD5;
        //Check if the Imagefile instance is an image. If so, check if it's already in the pMap.
        if (Utils.isImage(f)) {
            MD5 = Utils.toMD5(f);
            if (!SyncFolderMapImpl.MD5Map.containsKey(MD5)) {

                System.out.println("Adding " + f.getName() + " to DB");
                add(new PhotoDTO(f.getPath(), MD5, albumName));
            }
        }
Run Code Online (Sandbox Code Playgroud)

这是MD5:

  public static String toMD5(File file) throws IOException, NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("MD5");
    FileInputStream fis = new FileInputStream(file.getPath());


    byte[] dataBytes = new byte[8192];

    int nread = 0;
    while ((nread = fis.read(dataBytes)) != -1) {
        md.update(dataBytes, 0, nread);
    }

    byte[] mdbytes = md.digest();

    //convert the byte to hex format method 2
    StringBuffer hexString = new StringBuffer();
    for (int i = 0; i < mdbytes.length; i++) {
        String hex = Integer.toHexString(0xff & mdbytes[i]);
        if (hex.length() == 1) hexString.append('0');
        hexString.append(hex);
    }
    return hexString.toString();
}
Run Code Online (Sandbox Code Playgroud)

编辑:尝试使用 FastMD5。相同的结果。

public static String toMD5(File file) throws IOException, NoSuchAlgorithmException {

    return MD5.asHex(MD5.getHash(file));
}
Run Code Online (Sandbox Code Playgroud)

编辑2尝试使用ThreadLocal和BufferedInputStream。我仍然有很多内存使用情况。

private static ThreadLocal<MessageDigest> md = new ThreadLocal<MessageDigest>(){
     protected MessageDigest initialValue() {
         try {
             return MessageDigest.getInstance("MD5");
         } catch (NoSuchAlgorithmException e) {
             e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
         }
         System.out.println("Fail");
         return null;

     }
};


private static ThreadLocal<byte[]> dataBytes = new ThreadLocal<byte[]>(){

    protected byte[] initialValue(){
     return new byte[1024];
    }

};

public static String toMD5(File file) throws IOException, NoSuchAlgorithmException {

    //        MessageDigest mds = md.get();
    BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));


    //        byte[] dataBytes = new byte[1024];

    int nread = 0;
    while ((nread = fis.read(dataBytes.get())) != -1) {
        md.get().update(dataBytes.get(), 0, nread);
    }

    byte[] mdbytes = md.get().digest();

    //convert the byte to hex format method 2
    StringBuffer hexString = new StringBuffer();
    fis.close();
    System.gc();
    return javax.xml.bind.DatatypeConverter.printHexBinary(mdbytes).toLowerCase();




     //        return MD5.asHex(MD5.getHash(file));
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*n C 5

如何使我的代码尽可能高效?

简而言之:简介它!

让您的代码正常运行,然后在一组典型的输入文件上运行时对其进行分析。用它来告诉您性能热点在哪里。

如果我这样做,我会首先从单线程版本开始,并针对这种情况进行调整。然后我会慢慢增加线程数量,看看性能如何变化。一旦达到“最佳点”,请重新进行分析并查看现在的瓶颈所在。


实际上很难预测性能瓶颈在哪里。这将取决于平均文件大小、拥有的核心数量、光盘的速度以及操作系统可用于预读缓冲的内存量等因素。还有,您正在使用什么操作系统。

我的直觉是线程的数量将相当重要。太少,CPU 就会闲置,等待 I/O 系统从磁盘中获取内容。太多,您会使用额外的资源(例如线程堆栈的内存),但没有真正的好处。像这样的应用程序可能会受到 I/O 限制,并且大量线程无法解决这个问题。


您是这样评论的:

性能问题纯粹是内存问题。我很确定我创建 MD5 哈希值的方式存在问题,因此浪费了内存。

我在您提供的代码中看不到任何会使用大量内存的内容。您生成哈希值的方式没有什么严重错误。AFAICT,您的代码可能导致内存使用问题的唯一方法是:

  • 你有很多很多线程都在执行该代码,或者
  • 你在内存中保存了很多很多的哈希值(和其他东西)。(你没有向我们展示add正在做什么。)

但我的建议是类似的,使用内存分析器并诊断它,就好像它是存储泄漏一样,从某种意义上来说,确实如此!