使用VB6查询可以更快地遍历目录:缓存和Ram问题?
时间:2020-03-06 14:47:50 来源:igfitidea点击:
下面是一个相当简单的函数,它计算一台计算机上有多少个文件。调用" C:",大约需要5秒钟才能运行。除非我有一段时间没有运行它,或者除非先运行一个清除内存程序,否则要花60秒钟或者更长时间。我不会以为它可以缓存,因为每次都进行新的扫描(即,启动程序的新实例,因为它所做的只是此扫描),但是也许与内存分配有关?关于如何使这种快速运行每次发生的任何想法,或者为何无法做到这一点的任何想法?其他程序(例如SpaceMonger)即使在清除RAM或者在运行之间等待很长时间后,也能在10秒内获得文件总数。因此,绝对有一种方法可以做到这一点,尽管在VB中不一定如此。
Private Function countFiles(Name As String) As Long On Error GoTo ErrorHandler DoEvents Const CurMthd = "countFiles" Dim retval As Long 13 Dim FindData As win.WIN32_FIND_DATA 14 Dim SearchPath As String 15 Dim FileName As String 17 Dim SearchHandle As Long If Right(Name, 1) <> "\" Then Name = Name & "\" 19 SearchPath = Name & "*.*" 20 SearchHandle = win.FindFirstFile(SearchPath, FindData) Do DoEvents ' g_Cancel = True If g_Cancel Then countFiles = retval Exit Function End If 22 If SearchHandle = win.INVALID_HANDLE_VALUE Or SearchHandle = ERROR_NO_MORE_FILES Then Exit Do 23 FileName = dsMain.RetainedStrFromPtrA(VarPtr(FindData.cFileName(0))) 24 If AscW(FileName) <> 46 Then If (FindData.dwFileAttributes And win.FILE_ATTRIBUTE_DIRECTORY) Then retval = retval + countFiles(Name & FileName) Else retval = retval + 1 End If 28 End If 29 Loop Until win.FindNextFile(SearchHandle, FindData) = 0 win.FindClose SearchHandle countFiles = retval Exit Function ErrorHandler: Debug.Print "Oops: " & Erl & ":" & Err.Description Resume Next End Function
解决方案
操作系统本身缓存从磁盘读取的数据。这完全在程序之外,我们实际上对其没有任何控制权。因此,当我们运行"清除内存"程序时,它将清除这些缓存。这就是为什么我们可以看到那些"清除RAM"程序通常完全没有用的原因,通过清空缓存,它会使程序运行速度变慢。