我正在使用nlohmann库来解析JSON代码。我们有两个问题:
1- 为什么nlohmann使用巨大的内存来解析数据
2- 在本地函数中调用解析器后,就像下面的代码一样,它不会释放内存。我的JSON数据大小约为 8MB,解析器使用超过50MB进行解析。我解析了这个JSON数据10次,内存使用量上升到600MB,函数完成后内存没有释放。
#include "nlohmann/json.hpp"
#define REPEAT 10
void GenerateNlohmann() {
std::string filePath{FILE_ADDRESS};
std::ifstream iFile(filePath.c_str(), std::ios::in);
std::string data{};
if (iFile.is_open()) {
data = std::string((std::istreambuf_iterator<char>(iFile)),
std::istreambuf_iterator<char>()); // About 8MB size
iFile.close();
}
if (!data.empty()) {
nlohmann::json json = nlohmann::json::parse(data); // Use memory about 50MB
std::vector<nlohmann::json> jsons{};
for (int i = 0; i < REPEAT; ++i) {
nlohmann::json j = nlohmann::json::parse(data);
jsons.emplace_back(j);
}
while (!jsons.empty()) {
jsons.pop_back();
}
}
}
int main() {
GenerateNlohmann();
// Now memory usage is about 600MB
std::cout << "Input a numberto exit" << std::endl;
int i;
std::cin >> i;
return 0;
}