Big O Notation is often ignored by developers. However, It is a fundamental notion, very helpful and very easy to understand.

Let’s learn in few minutes what is it.

## The Big O Notation

Big O Notation (or algorithmic complexity) is a standard way to measure the performance of an algorithm. It uses a mathematical way to judge the effectiveness of your code.

Don’t be too afraid by the word “mathematical”. It is only basic operations you already know.

This notation allows you to measure the evolution of the growth rate of your algorithm compared to the input data. It will describe the worst possible case in terms of performance of your code.

The power of this notation is to be able to measure the efficiency of an algorithm without being affected by an external event such as bad connection, hardware stuff, etc. It is based on a single criterion: the number of operations to be performed.

## A Basic Example

Let’s discover a basic example to really understand what is this notation.

Imagine you are in an interview for a job. One of the technical test is to create a function which takes as input a number n and which returns the sum of the numbers from 0 to n.

A naive implementation would be to iterate from 0 to n, and perform an addition at each iteration.

Basic example using JavaScript

If I received 10 as input, I will have 10 iterations. If I got 1 million as input, I will have 1 million iterations. The number of iteration is equal to the input given.

We have a linear execution time. We can say that this algorithm has a complexity of O(n). The number n in parentheses means the number of iteration to performed is equal to the input.

The best solution for this exercise is to use the famous method n * (n + 1) / 2.

Basic example optimized

Using this solution, whatever is the number given, there will be only one operation. The algorithm requires a constant time to execute, we say we have a complexity of O(1).

In this case, O(1) doesn’t necessarily means the algorithm is very fast. It can take few nanoseconds (like with our `sumFrom0ToN` function) or three minutes, depending on what the function does. What it means is the algorithm requires a constant time to execute no matter the amount of data given in input.

#optimization #javascript #algorithms #software-engineering #programming

1.40 GEEK