After lots of testing, I found the answer to my questions with the following code:
#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;
}
)");
}
I ran the code using MSVC, and looked at the runtime statistics to figure out what happened in the RAM: Runtime Statistics
The code works reasonably. After a startup phase, 1GB of RAM is allocated for the data
object. In the loop, the RAM stays at 2GB, because we also have the new_data
object. After the loop, it falls down to 1GB.
Therefore, the answers to my questions are:
- chaiscript does indeed delete the data after each looping of the for statement.
- chaiscript does delete the data after the loops as well.
- Yes, you need to check that the c++ functions do not create unnecessary data. For example, if you write with a copy instead of a reference --
update_structure(int i, std::vector<int> data)
, then the function will use a copy of data, and therefore the RAM will jump to 3GB in the loop.
- chaiscript does not delete unused data inside the same block. (
new_data
is deleted after the loop, but not data
.)