Squeezing performance from your application
Introduction
Performance is a very important concept in computer science that has to do with efficiency of a system. The more performant a system is, it means it is able to effectively handle much load with less effort. In the case of software, we need to make sure that our infrastructure, application code and database can all work together to ensure that lots of requests are properly handled.
In this article, we will look at addressing performance bottlenecks at the level of the application and at the level of the database.
Application Level performance
The application is the most obvious level where performance can be addressed. Asides from writing good and clean dry code, we need to be sure that that we are using the right set of data structures for every operation.
Basic clean code
Use the right data type for the right variable.
When working with lists, you should be careful with the size and parsing of this list. Some languages like PHP handling parsing of arrays via references while other languages like Go gives you the freedom to pass slices and maps either by copying of by reference. Know when to use one over the other.
In most cases, you want to use a
uintinstead of anintdata type. You should also consider this scenario too.Avoid nested loops as much as possible. Use built-in functions for arrays and lists data types to get the best performance out common operations.
Recursion can be a good approach to solving some problems better. If you get the chance, use it as well.
Caching
Better not to cache at all than to cache the wrong data.
Caching is one of the most obvious ways to drastically improve code performance by a mile. Introducing Redis cache is a very good idea. Always make sure you are also caching the right data because it is better not to cache at all, than to cache the wrong data. You should also properly handle cache invalidation. The most common of them is TTL or by adding a fallback to allow only one request to refresh the cache. You could also refresh the cache before the invalidation time set.
You should only add a cache when you notice there are performance issues of if your application is suddenly handling more requests than it should be.