我正在尝试编写一个程序,将C:驱动器上的每个文件和文件夹名称添加到ArrayList。该代码可以正常工作,但是由于大量的递归,它变得非常缓慢。这是代码:

public static void updateFileDataBase()
{
    ArrayList<String> currentFiles = new ArrayList<String>();
    addEverythingUnder("C:/",currentFiles,new String[]{"SteamApps","AppData"});
    for(String name : currentFiles)
        System.out.println(name);
}
private static void addEverythingUnder(String path, ArrayList<String> list, String[] exceptions)
{
    System.gc();
    System.out.println("searching " + path);
    File search = new File(path);
    try
    {
        for(int i = 0; i < search.list().length; i++)
        {
            boolean include = true;
            for(String exception : exceptions)
                if(search.list()[i].contains(exception))
                    include = false;
            if(include)
            {
                list.add(search.list()[i]);
                if(new File(path + "/" + search.list()[i]).isDirectory())
                {
                    addEverythingUnder(path + "/" + search.list()[i],list,exceptions);
                }
            }
        }
    }
    catch(Exception error)
    {
        System.out.println("ACCESS DENIED");
    }
}


我想知道是否有什么我可以做来加快这个过程。提前致谢 :)

最佳答案

程序由于递归而变慢


不,不是。递归不会使事情变慢。较差的算法和不良的编码会使事情变慢。

例如,对于要处理的每个文件,您要调用Files.list()四次,而对于每个目录,则要调用一次。您可以通过对每个目录执行一次操作来保存O(N):

   for(File file : search.listFiles())
    {
        String name = file.getName();
        boolean include = true;
        for(String exception : exceptions)
            if(name.contains(exception))
                include = false;
        if(include)
        {
            list.add(name);
            if(file.isDirectory())
            {
                addEverythingUnder(file,list,exceptions);
            }
        }
    }

09-25 20:55