我正在使用以下函数枚举 vector 中特定键和子键的所有注册表键并返回它。
但是对于大的Key Values,这段代码运行起来似乎很慢,比如超过200000+的keys,需要超过5分钟才能完成。 只是想知道我怎样才能让它更有效率。
vector<string> CRegistryAPI::EnumKeys(HKEY RootKey, string SubKey)
{
DWORD keyLen = 255;
int index = 0;
int ret = 0;
PFILETIME lastWrite = 0;
HKEY hKey = 0;
char keyName[255];
vector<string> keyList;
if (RegOpenKeyExA(RootKey, SubKey.c_str(), 0, KEY_ENUMERATE_SUB_KEYS,&hKey) != ERROR_SUCCESS)
return keyList;
do
{
ret = RegEnumKeyExA(hKey, index, keyName, &keyLen, 0, 0, 0, lastWrite);
if (ret == ERROR_SUCCESS)
{
keyList.push_back(keyName);
}
index ++;
keyLen = 255;
}
while (ret == ERROR_SUCCESS);
if (hKey != NULL)
RegCloseKey(hKey);
return keyList;
}
感谢任何帮助。谢谢。
最佳答案
您可以做的一项优化是使用 RegQueryInfoKey()
在枚举其内容之前查询有关给定键的信息。例如,您可以预先分配 vector 的容量,这样它就不必在枚举期间多次重新分配:
RegQueryInfoKey(hKey, 0, 0, 0, 0, 0, 0, &dwNumValues, 0, 0, 0, 0);
keyList.reserve(keyList.size()+dwNumValues);
此外,您的枚举无法确保您的缓冲区在将其插入 vector 时以 null 结尾。即使是,您的推送方式目前也需要 std::string
每次都计算缓冲区长度。您应该改用返回给您的缓冲区长度:
keyList.push_back(string(keyName, keyLen));
关于c++ - 枚举所有注册表项的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23185069/