# Performance tips

This tutorial explains how to write performant JuMP code.

Tip

Read the Performance tips section of the Julia manual. The most important rule is to avoid global variables!

## Use macros to build expressions

### What

Use JuMP's macros (or add_to_expression! to build expressions. Avoid constructing expressions outside the macros.

### Why

Constructing an expression outside the macro results in intermediate copies of the expression. For example,

x[1] + x[2] + x[3]

is equivalent to

a = x[1]
b = a + x[2]
c = b + x[3]

Since we only care about c, the a and b expressions are not needed and constructing them slows the program down!

JuMP's macros rewrite the expressions to operate in-place and avoid these extra copies. Because they allocate less memory, they are faster, particularly for large expressions.

### Example

model = Model()
@variable(model, x[1:3])
3-element Array{VariableRef,1}:
x[1]
x[2]
x[3]

Here's what happens if we construct the expression outside the macro:

@allocated x[1] + x[2] + x[3]
94911
Info

The @allocated measures how many bytes were allocated during the evaluation of an expression. Fewer is better.

If we use the @expression macro, we get many fewer allocations:

@allocated @expression(model, x[1] + x[2] + x[3])
640