# Code complexity, loops and stuff.

• 0 favourites

### Stats

70 visits, 89 views

### Translations

This tutorial hasn't been translated.

## LÖÖPS

Loops are very important in programming. They do stuff. They're cool.

Loops have a finite number of iterations. Because nothing is infinite within the physical limitations of computers. Not even Minecraft or No Man's Sky. Don't trust these marketing lies.

Anyway, because Math exists, we usually refer to that general concept of "number of iteration" as a math formula based around "n". "n" being the number of things you're dealing with.

So. Let's get to the point: Loops do stuff, and they can do it more or less efficiently. That efficiency is named "Code complexity". Essentially, the number of steps the computer needs to take to get something done.

A very common example is the number of ways to sort an array of "n" elements.

Subscribe to Construct videos now

In this case, "n" refers to the number of elements of the array, and the code complexity is the number of steps the algorithm took based on n. So if an algorithm needs to go through every element only once, it's complexity is just "n". If it needs to go through every element, and every time an element is treated it needs to go through every other element, it has a complexity of "n²".

## Complexity is easy to grasp

I'm using the example of arrays to demonstrate what I mean, but most loop based algorithms have the same complexity issues to deal with, and optimizing that kind of algorithm comes down to doing the given task in a minimum of steps. Find a way to reduce the amount of checks you make, and you'll get much better results.

One example of this is how Construct manages collisions. Instead of checking collisions between every objects (essentially n² complexity for n objects), it divides the layout in cells and only checks collisions per cell plus some edge cases.