Improve the performance for enumerating files and folders using .NET

后端 未结 7 1435
一生所求
一生所求 2020-12-08 07:51

I have a base directory that contains several thousand folders. Inside of these folders there can be between 1 and 20 subfolders that contains between 1 and 10 files. I\'d

7条回答
  •  隐瞒了意图╮
    2020-12-08 08:41

    This is (probably) as good as it's going to get:

    DateTime sixtyLess = DateTime.Now.AddDays(-60);
    DirectoryInfo dirInfo = new DirectoryInfo(myBaseDirectory);
    FileInfo[] oldFiles = 
        dirInfo.EnumerateFiles("*.*", SearchOption.AllDirectories)
               .AsParallel()
               .Where(fi => fi.CreationTime < sixtyLess).ToArray();
    

    Changes:

    • Made the the 60 days less DateTime constant, and therefore less CPU load.
    • Used EnumerateFiles.
    • Made the query parallel.

    Should run in a smaller amount of time (not sure how much smaller).

    Here is another solution which might be faster or slower than the first, it depends on the data:

    DateTime sixtyLess = DateTime.Now.AddDays(-60);
    DirectoryInfo dirInfo = new DirectoryInfo(myBaseDirectory);
    FileInfo[] oldFiles = 
         dirInfo.EnumerateDirectories()
                .AsParallel()
                .SelectMany(di => di.EnumerateFiles("*.*", SearchOption.AllDirectories)
                                    .Where(fi => fi.CreationTime < sixtyLess))
                .ToArray();
    

    Here it moves the parallelism to the main folder enumeration. Most of the changes from above apply too.

提交回复
热议问题