# Cplex C++ Interface: How to add many constraints quickly?

I noticed that adding constraints to an IloModel one by one can be prohibitively slow. (I am referring to the construction of the model, not the optimization.)

Suppose I have many constraints with the same number of variables, can I add the constraint matrix in one function call?

Are there other ways to speed up the construction of the model?

I came across this issue recently, and discovered that if you first add the constraints to an IloRangeArray, and then add that object to the model, you'll see a significant speed-up. Removing constraints is also faster if they are contained in a container object like an IloRangeArray.

I was struggling with similar issue recently and noticed that for some reason working with IloRange is much slower than using IloNumExpr. Previously I was adding constraints as follows:

IloEnv env;
IloNumVarArray vars(env, stl_vars.size(), 0, IloInfinity);
IloRangeArray constrs(env, stl_constrs.size(), 0, 1);
for (size_t i = 0; i < stl_constrs.size(); ++i) {
constrs[i].setUB(stl_constrs[i].ub);
for (size_t j = 0; j < stl_constrs[i].vars.size(); ++j)
constrs[i].setLinearCoef(vars[stl_constrs[i].vars[j].ind], stl_constrs[i].vars[j].coefficient);
}


Replacing this code with the following:

IloEnv env;
IloNumVarArray vars(env, stl_vars.size(), 0, IloInfinity);
for (size_t i = 0; i < stl_constrs.size(); ++i) {
IloNumExpr row(env);
for (size_t j = 0; j < stl_constrs[i].vars.size(); ++j)
row += stl_constrs[i].vars[j].coefficient * vars[stl_constrs[i].vars[j].ind];