We all want our software to run fast and smoothly. Some will say that is nothing new and no challenge at all. After all, computers keep getting more powerful and internet connections more reliable, so everything will automatically run faster. Let's stop right there.
It is true that technology keeps getting better and so does the speed that comes with it. But let's not forget that:
- users' expectations are growing too: they used to be able to wait 8 seconds for a page, and today 3 is already "long",
- programmers' "laziness" is growing, also because of the sheer number of tasks,
- databases store more and more information,
- a very large amount of data will always be a problem, regardless of the environment.
So yes, sometimes upgrading or expanding the infrastructure (using the ability to scale software) will be enough, but it can also be very shortsighted, especially if the amount of data keeps growing. Eventually there will be no other way than to get to work on the heroine of today's text: optimization.
Today we will talk in general terms about this topic, which on one hand can be fascinating and is a gripping detective puzzle for some programmers. But we must remember the other side of the coin: it is usually devilishly hard and does not always end in success. That is why one goal of this article is to outline the topic for non-technical people, so that they know optimization work can be complicated, takes a lot of time, and the results are sometimes not very spectacular.
What is optimization, really?
For most people the word "optimization" means making software run faster, and that is the right way of thinking. Formally, it is an action that lets you achieve the greatest possible effects with the fewest possible resources, and in mathematics it is a way of finding a solution while respecting given constraints (definitions from the PWN Dictionary of the Polish Language). We will stick with the first definition.
Optimization is usually needed when an application runs slowly, noticeably getting in the way of users who want to use the available features comfortably. In extreme cases the users of the software cannot use all of the system's functions at all because of problems related to slowness (for example request timeouts). It usually happens at certain moments and under specific conditions, which are unfortunately sometimes hard to identify and reproduce. In such a situation, optimization efforts aim, of course, to speed up the application, because low speed is no longer just a technical problem but also a business one: practically no user will want to pay for something that takes a great deal of patience to use.
But time is not always the only criterion. Sometimes the problem is excessive memory use, which makes the program freeze. For example, generating a report as an XLSX file with a very large amount of data may require allocating a very large amount of RAM, which the server may not be able to provide. Of course, the solution may be to add memory, but as I wrote before, that is shortsighted, because mountains of data keep growing and sooner or later the added memory will not be enough either.
Time and memory are usually opposing criteria: many techniques for reducing running time use more memory than normal, and vice versa. Of the two, memory is usually the more available resource today, so applications are often sped up at the cost of disk space or RAM so that the user waits less for the results. It is important to remember, though, that finding a compromise point is essential.
Why not optimize from the very beginning?
That is a good question, even if it seems odd to some. After all, optimizing from the start means that, admittedly, progress may be a bit slower in the early stages, but the problem will not show up later and we will save ourselves all the stress, right? Well, no.
With the development of programming tools and development teams, what is valued today is good architecture and readable code that all developers can find their way around. And it is worth remembering that a technical team does not consist only of veterans who have been with the project from the start. Very often more programmers join the project or come back to it after a longer time, and their skill levels differ. So it is very important to keep the project clean and write it in an understandable way. On the other hand, this does not always go hand in hand with speed: many optimization tricks make code more convoluted and introduce fragments that new people will not understand without extra explanation.
Another thing is that we cannot foresee everything at the start. Even with many years of experience, programmers can still be surprised. Applications are very different, they run in different conditions, and people have different needs that they cannot always express in advance. That is why we should not count on identifying all potential problems at the start and designing preventive measures for them.
Additionally, the truth is that unless we are building a system of critical strategic importance or a fast-paced game, there is no point in optimizing every fragment. For example, suppose we maintain a web application in which a page loads in 8 seconds and consists of many HTTP requests. Analyzing those requests, we see unnecessary operations in one of them that could be shortened. Of course, if it is a matter of a minute of work (including verification), it can probably be done without delay. But if we see that hours would go into the change and into checking that nothing functionally broke, we should look at how long the given request takes. If it is a large part of the page load and the change will noticeably shorten those 8 seconds, it absolutely makes sense. But if it is a matter of saving 10 milliseconds, there is no need to change it, at least not first. Unless, of course, that small change here will help bigger areas elsewhere and pave the way for further optimizations.
All this makes true the statement attributed to the legendary professor Donald Knuth:
Premature optimization is the root of all evil
It sounds funny, and quoting it has more than once brought a smile to clients' faces, but the fact is that it is a very practical rule. There is no need to worry about optimization on an ongoing basis, especially at the expense of code readability and the development of the architecture. First, "dirtying" the project from the start does not serve correct results and progress, which everyone wants to see, the client most of all. Second, performance problems usually do not show up in the first phases. Some time has to pass and the system has to fill up with data before performance problems can be observed and their source found. In the end it may turn out that those problems never appear, and then premature optimization will simply have been a waste of time.
Of course, this does not mean that you should not use various painless constructs from the start that come from experience. If, based on other projects, we have found that, say, proper management of translations is not complicated and contributes to better performance, it is worth applying it right away, especially since structural changes are the worst and most labor-intensive in the later stages of IT projects. As usual, it is a matter of knowledge and past projects that shape our thinking, mostly, unfortunately, through failures. But as I mentioned before, let's not count on foreseeing everything.
As an example of how small optimizations can be questionable from the point of view of code readability, we can point to a famous fragment of the game Quake III Arena, concerning the calculation of the inverse square root. Of course, in a fast-paced online shooter built on speed, such micro-optimizations matter enormously (especially since they concern frequently occurring situations), but this applies to a small share of projects.
How do you find the places to optimize?
Most often it starts with the observation that the system is running slowly and something has to be done about it. That is not enough, though: you have to know what exactly is slowing it down. Of course, there may be a situation where the problem is a key feature used on every page, so the problem is really "everywhere". But even then, as in most cases, you need to isolate the places where the performance drop is noticeable. How do you do that?
First of all, for web applications browsers offer a wonderful tool called developer tools. It is an overlay you can use to do many things: inspect the data stored by the page, see the JavaScript console, temporarily change fragments of HTML code, and also monitor the HTTP requests happening in the background. The last one is extremely important when investigating optimization, because for every request the time and the moment it was made are displayed. This lets you see whether, on a page that loads for 10 seconds, only one request takes that long or several requests add up to it. That way you can find a starting point for further, more specific actions.
The second matter is more precise measurements. Most often it turns out that even if one request takes about 8 seconds, most of that time falls on a specific set of instructions. It cannot be denied that the culprit is most often a database query. You can confirm this with profiling tools, which let you measure individual intermediate times in the code. Well, "tools" is a grand word: often the same effect can be achieved by adding appropriate logging, whose results can be read later from log files. Many frameworks offer this, and you can always write your own code to make the process easier.
Finally, if the analysis shows that many areas affect how fast a page loads, take a close look at whether they share a single common source. It is easy to imagine a situation in which successive steps of a process in a web application run slowly, but only because at every stage the same object is fetched in the same way and that one request is slow. In that case it may turn out that only one aspect of the system really needs to be fixed, and it should "unblock" the rest. Whether that is an easy task is a completely different matter.
After finding such places, it is worth making a priority list and planning the work accordingly. It often happens that bigger optimization efforts are so tied to the internal mechanisms of a given application that they make it harder (and in extreme cases impossible) to develop features or make quality fixes at the same time. In addition, optimizing two places at once may be possible, but there are also cases in which work on one fragment significantly affects the other. Trying to implement changes in both places at once is a recipe for disaster. Unfortunately, everything depends on the specific case here, and there is no single rule.
Main optimization techniques and areas
This is really a topic for a whole separate article (or even a book), because there are many such areas and both they and the techniques used are strictly tied to the given case, technology and the application itself. There is no single universal way to improve performance, just as there is no single recipe for a successful project or movie. Of course, there are some general rules to follow and options whose enabling or disabling helps achieve better results, but you will not find a tutorial that tells you straight how to optimize your application and solves exactly the problem you have with it.
Most often optimization concerns the database and queries. Connecting the application to the database takes some time in itself (which is why the number of such operations is limited), but the real killers are complex queries on normalized schemas. Let me say right away that databases are normalized for the sake of clarity and data consistency, and it is a good practice in general. Unfortunately, a side effect is that it leads to many joins or subqueries, and this can create performance difficulties. Fortunately, there are plenty of techniques, from improving the queries themselves, through splitting them into smaller ones (they do not always have to be run for every row), to indexes or setting the right parameters. Unfortunately, that does not mean it is easier: with a given database structure, some changes are often extremely hard and time-consuming to carry out. It is a little easier with problems caused by a huge amount of data, since caching can help a lot here, though it has its consequences too.
Of course, it may happen that the code itself is written inefficiently, and on closer analysis the programmer identifies loops run many times, unnecessary conditional statements, constant fetching of the same data and so on. For me these are usually the most pleasant optimizations, because they are fairly clear and do not require big changes in the database. Sometimes they involve code smells, and speeding things up is also an opportunity to refactor, although, as I mentioned before, it is often optimization itself that leads to dirty code in the name of faster execution.
Analyzing requests, you can also find places where several requests can be combined into one. For example, if the frontend sends the backend 6 requests, each returning different information but all based on a single database query, it is worth considering whether that information could be fetched once and returned in a shared response, so the query runs only once. Of course, this is not always possible, but when it is, the system often suddenly gets much faster.
It may also turn out that the problem is not the backend but the frontend. The trouble may lie not in the data or complex logic but, for example, in inefficient sending of HTTP requests or in waiting for resources such as images, JavaScript scripts or CSS styles to load. Fortunately, there are many techniques here as well, and the browser itself helps by caching resources that have already been downloaded.
Finally, perhaps the application is fine, but the hardware or configuration it runs on is too weak or set up badly. Of course, investing in stronger hardware is hard to call optimization, because it is simply adding power, which, remember, is not always the solution. But the configuration is sometimes worth looking into, as long as you have access to it. This applies especially to systems whose traffic comes from very many sources. The difficulty here may be the handling and knowledge of the parameters, because this is usually not an area where programmers are experts, so a consultation with an administrator may be useful.
How can you avoid optimization?
I mentioned that with experience you can learn to build systems in a way that "preserves" some performance from the start and dodges problems in the future.
First of all, this concerns the architecture and preparing it for possible scaling. Remember, though, that this applies to really large systems that will serve many users at once. It does not mean scaling is forbidden for smaller software; it is simply less cost-effective there. You should also seriously consider splitting the system into a frontend and a backend to have more flexibility in later deployments.
Various database tricks can also help avoid the need for optimization. Merging certain tables means fewer joins in queries, so if it does not hurt consistency, it is worth spending some time on that reduction. Likewise, for frequently repeated subqueries you can consider additional columns holding current sums or averages, but that may bring a risk of information that does not match.
Finally, when creating a project it is worth identifying things that can be stored in a cache and have their results replayed from it. Paradoxically, this may lead us to the point where it turns out that some things are not worth storing in the database at all, and so there is no need to reach into it for information. Again, though, careless action can lead to inconsistency.
Summary
We have certainly not exhausted the topic of optimization today. It is too broad and also too individual. Caching, for example, needs a longer discussion, since it is often the answer to many problems but has side effects that are not always acceptable. Still, I hope I have outlined the topic and explained why it is not so simple, not so obvious, and sometimes simply needed. On the other hand, to be fair, it is very satisfying, and well-done optimization gives every programmer an incredible feeling of victory and the client simply relief.
Best regards and thank you, Jakub Rojek.


