经过大量测试,我用以下代码找到了我的问题的答案:
#include <vector>
#include <chaiscript/chaiscript.hpp>
std::vector<int> create_big_structure() {
//This is 1GB in size.
return std::vector<int>(268435456);
}
std::vector<int> update_structure(int i, const std::vector<int>& data) {
//This is 1GB in size.
return std::vector<int>(268435456);
}
void output_data_evolution(const std::vector<int>& data, const std::vector<int>& new_data) {}
int main() {
chaiscript::ChaiScript chai;
chai.add(chaiscript::fun(&create_big_structure), "create_big_structure");
chai.add(chaiscript::fun(&update_structure), "update_structure");
chai.add(chaiscript::fun(&output_data_evolution), "output_data_evolution");
chai.add(chaiscript::bootstrap::standard_library::vector_type<std::vector<int>>("VectorInt"));
chai.eval(R"(
var max = 5;
var data = create_big_structure();
for (var i = 1; i < max; ++i)
{
var new_data = update_structure(i, data);
output_data_evolution(data, new_data);
data = new_data;
}
)");
}
我使用 MSVC 运行代码,并查看运行时统计信息以了解 RAM 中发生的情况:运行时统计信息
该代码工作合理。在启动阶段之后,会为data
对象分配 1GB 的 RAM。在循环中,RAM 保持在 2GB,因为我们也有new_data
对象。在循环之后,它下降到 1GB。
因此,我的问题的答案是:
- chaiscript确实会在 for 语句的每次循环后删除数据。
- chaiscript 也会在循环之后删除数据。
- 是的,您需要检查 c++ 函数是否不会创建不必要的数据。例如,如果您使用副本而不是引用进行写入 --
update_structure(int i, std::vector<int> data)
,则该函数将使用数据副本,因此 RAM 将在循环中跳转到 3GB。
- chaiscript不会删除同一块内未使用的数据。(
new_data
在循环后被删除,但不是data
。)