Performance optimization is a hot topic in C++ language. I'm going to talk about this topic from simple to advanced techniques in a series of articles. Some tips can be simple but from a performance point of view the impact can be huge.
We can call performance optimization as improving the readability of the code to the machine or computer. Before getting into performance optimization topic I would like to highlight some facts. It all depends on the application and the usage of the application. Not all code segments needs to optimized 100% in order to run your application faster. For some application we might not need optimized code. For those cases I would highly recommend to aim for readability. I will be talking about this in a separate article.
In this article I'm going to highlight the importance of using the best algorithm. This is a basic thing but most new developers tend to ignore this possibly due to lack of knowledge and experience. If you are writing a code for some problem first you should identify or implement the best algorithm for the solution. Once you found the best algorithm you can move on to improve the performance of that algorithm. If you start with a low performing algorithm and try to optimize, it will be a waste of time.
Let's look at a simple example where we need to write a code to find the sum of numbers from 0 to 100. Below are some ways to obtain the answer.
In the above code we have solved the problem with 3 different ways. First one using is using a loop, second one is using recursion and the last method is using mathematics. As you can clearly see the last method will be the best algorithm to solve this problem. And it will be a waste of time implementing the first or the second method and trying to optimize it.
As per the example we have to find the best algorithm to solve the problem using the knowledge in the industry where you are trying to solve the problem in. In this case it's a maths problem and we use our knowledge in mathematics to find the best solution.
One important thing to note is when it comes to performance we should always measure the performance in the real production environment rather than depending solely on the theories. Some theories might not work in all the conditions.
If you find this article useful please leave a comment below. If you find anything controversial or missing in this article we can discuss in the comments section.