Given the following data structures, we show how to construct constraints most efficiently:
You should use addTerms() to construct a linear expression in a single function call. According to the Gurobi documentation this is the most efficient way:
- You should avoid using expr = expr + x in a loop. It will lead to runtimes that are quadratic in the number of terms in the expression.
- Using expr += x (or expr -= x) is much more efficient than expr = expr + x. Building a large expression by looping over += statements is reasonably efficient, but it isn't the most efficient approach.
- The most efficient way to build a large expression is to make a single call to addTerms.
GRBLinExpr expr = 0;
expr.addTerms(&a, &x, x.size());
You can add the linear expression as a constraint using:
model->addConstr(expr <= 0)
Concerning adding multiple constraints in one call (documentation about addConstrs):
We recommend that you build your model one constraint at a time (using addConstr), since it introduces no significant overhead and we find that it produces simpler code. Feel free to use these methods if you disagree, though.