SSJX.CO.UK

# Programming - Math Loops

This guide will give you tips and ideas on how to improve the maths aspect of your programs. The focus of this guide will be maths in loops given that this will be the most time consuming and probably slowest part of your program.

### Original Program

This pseudo code loop is very common way to draw a block based level:

```var offsetx=48;
var offsety=48;
var actualx,actualy;

for (var j=0;j<10;j++)
{
for (var i=0;i<10;i++)
{
actualx=offsetx+(i*32);
actualy=offsety+(j*32);

// Draw our sprite at actualx,actualy
}
}
```

Perfectly functional but there are many ways to improve it. The following will highlight possible ways to do this.

### Reduce Calculations / Use Constants

Firstly the 'actualy' variable can be taken out of the inner loop. It gets calculated everytime but only changes when the 'j' changes. While we are here, both offsets do not change so we can help the compiler (and ourselves) by making them constants.

```const offsetx=48;
const offsety=48;
var actualx,actualy;

for (var j=0;j<10;j++)
{
actualy=offsety+(j*32);
for (var i=0;i<10;i++)
{
actualx=offsetx+(i*32);
// Draw our sprite at actualx,actualy
}
}
```

Now 'actualy' gets calculated 10 times instead of 100! In a more complex equation, it may be possible to precalculate parts of it and store it in a variable.

### Use Shifts

The compiler may automatically see that a '*32' is the same as a much quicker 'shift left by 5' and change it for us, but in case it does not:

```const offsetx=48;
const offsety=48;
var actualx,actualy;

for (var j=0;j<10;j++)
{
actualy=offsety+(j<<5);
for (var i=0;i<10;i++)
{
actualx=offsetx+(i<<5);
// Draw our sprite at actualx,actualy
}
}
```

Using sizes that work for Shifts is usually a good idea where possible.

### Avoid Multiplies (and Divides)

In general, multiplies and divides are slower than add and subtract. In this example, with a bit of rearranging, we can replace all the multiplies:

```const offsetx=48;
const offsety=48;

var actualx=offsetx;
var actualy=offsety;

for (var j=0;j<10;j++)
{
for (var i=0;i<10;i++)
{
// Draw our sprite at actualx,actualy
actualx+=32;
}
actualy+=32;
actualx=offsetx;
}
```

### Final Version

Here we have moved everything into the for loops. This has simplified the calculation side of thing as well as removed some variables and should be the quickest version of the original program:

```const offsetx=48;
const offsety=48;
var actualx,actualy;

for (actualy=offsety;j<(offsety+320);j+=32)
{
for (actualx=offsetx;i<(offsetx+320);i+=32)
{
// Draw our sprite at actualx,actualy
}
}
```

## Summary

Once you have your program working the next step is to optimise it, ideally without affecting its readability or maintainability. The condensed version of this page would be:

• Avoid repeated calculations of things that do not change.

• See if there is a better method. Optimising a bad method will only help so much.

Last updated 06/10/2018 