To get a trial key
fill out the form below
Team License (a basic version)
Enterprise License (an extended version)
* By clicking this button you agree to our Privacy Policy statement

Request our prices
New License
License Renewal
--Select currency--
* By clicking this button you agree to our Privacy Policy statement

Free PVS-Studio license for Microsoft MVP specialists
* By clicking this button you agree to our Privacy Policy statement

To get the licence for your open-source project, please fill out this form
* By clicking this button you agree to our Privacy Policy statement

I am interested to try it on the platforms:
* By clicking this button you agree to our Privacy Policy statement

Message submitted.

Your message has been sent. We will email you at

If you haven't received our response, please do the following:
check your Spam/Junk folder and click the "Not Spam" button for our message.
This way, you won't miss messages from our team in the future.

Code Optimization

Code Optimization

Aug 17 2017

Definition and Properties

Code optimization is any method of code modification to improve code quality and efficiency. A program may be optimized so that it becomes a smaller size, consumes less memory, executes more rapidly, or performs fewer input/output operations.

The basic requirements optimization methods should comply with, is that an optimized program must have the same output and side effects as its non-optimized version. This requirement, however, may be ignored in the case that the benefit from optimization, is estimated to be more important than probable consequences of a change in the program behavior.

Types and Levels of Optimization

Optimization can be performed by automatic optimizers, or programmers. An optimizer is either a specialized software tool or a built-in unit of a compiler (the so-called optimizing compiler). Modern processors can also optimize the execution order of code instructions.

Optimizations are classified into high-level and low-level optimizations. High-level optimizations are usually performed by the programmer, who handles abstract entities (functions, procedures, classes, etc.) and keeps in mind the general framework of the task to optimize the design of a system. Optimizations performed at the level of elementary structural blocks of source code - loops, branches, etc. - are usually referred to as high-level optimizations too, while some authors classify them into a separate ("middle") level (N. Wirth?). Low-level optimizations are performed at the stage when source code is compiled into a set of machine instructions, and it is at this stage that automated optimization is usually employed. Assembler programmers believe however, that no machine, however perfect, can do this better than a skilled programmer (yet everybody agrees that a poor programmer will do much worse than a computer).

What to Optimize

With manual code optimization, one faces another problem: one doesn't just need to know how exactly optimization should be done, but also what particular part of the program should be optimized. Due to various reasons (slow input operations, the difference in the working speed of a human operator and a computer, and so on), 90% of the execution time of a program is spent executing only 10% of the code (this statement is rather speculative, with the Pareto principle as a quite doubtful ground, but A. Tanenbaum makes it sound convincing). Since optimization takes additional time aside from the time you've spent on developing the program, you'd better focus on optimizing this time-critical 10% of code rather than try to optimize the whole program. These code fragments are known as bottlenecks, and can be detected by special utilities - profilers - which can measure the time taken by various parts of the program to execute.

In practice, however, optimization is usually done after the stage of "chaotic" programming (including such methods as "Copy-Paste", "we'll see later", "it's OK this way"), and therefore is a mixture of optimization as such, refactoring and bugfixes: simplification of "queer" constructs like strlen(path.c_str()), logical conditions like (a.x != 0 && a.x != 0), and so on. Profilers are of little help with this kind of optimization. Nevertheless, you can detect these issues with static analysis tools, i.e. tools designed to search for semantic errors, relying on deep analysis of source code. As you can see from the above mentioned example with the strange condition, inefficient code may appear as a result of errors (like a misprint in our example, where a.x != 0 && a.y != 0 should be instead). A powerful static analyzer will detect such code fragments and draw your attention to them by producing warning messages.

Good and Bad Outcomes of Optimization

In programming, almost everything should be treated from the viewpoint of rationality - optimization is no exception. There is a belief that code written by an inexperienced Assembler programmer is 3-5 times slower than code generated by the compiler (Zubkov). Widely known is a phrase by Knuth regarding early low-level optimizations (such as attempts to save on operators or variables): "Premature optimization is the root of all evil".

Most programmers don't complain about optimizations performed by the optimizer, some of which are conventional and obligatory. Such as, for instance, tail call optimization in functional languages (tail call is a special case of recursion, which can be represented as a loop).

However, one should understand that multiple complex optimizations at the level of machine code may cause a great slow-down of compilation. The benefit they allow you to gain may be much too insignificant, when compared to general system design optimizations (Wirth). One should also keep in mind that modern languages, with all their syntactic and semantic "frills", have many nuances and subtleties, so that a programmer who isn't familiar with them may be surprised by an outcome of optimization.

For example, take C++ and the so-called Return-Value Optimization, when the compiler avoids copying a temporary object returned by a function. Because the compiler omits copying, this method is also called "Copy elision". So, the following code:

#include <iostream>
struct C {
  C() {}
  C(const C&) { std::cout << "A copy was made.\n"; }
C f() {
  return C();
int main() {
  std::cout << "Hello World!\n";
  C obj = f();

may have several outputs:

Hello World!
A copy was made.
A copy was made.

Hello World!
A copy was made.

Hello World!

Strange as it may seem, all the three versions are valid because the language standard allows omitting calls of a copying constructor in such cases, even if the constructor has side effects (§12.8 Copying Class Objects, Paragraph 15).


Thus, we should always consider optimizing the program code using specialized utilities wherever possible, yet do this with much care, and be ready for the probability of unexpected tricks from the compiler at times.


A set of diagnostics is implemented in the static analyzer PVS-Studio that enable you to find some situations where code can be optimized. However, PVS-Studio as any other static analyzer cannot serve as a replacement of the profiling tools. Only dynamic program analyzers are able to identify the bottlenecks. Static analyzers do not know what input data programs get and how often a particular piece of code is executed. That is why we are saying that the analyzer suggests implementing some "micro-optimizations" of code, which do not guarantee the performance gains.

Despite the considered disadvantage, PVS-Studio analyzer acts as a good complement to profiling tools. Moreover, when dealing with PVS-Studio warnings, related to optimization, code often becomes simpler and shorter. This effect is considered in more detail in the article "Exploring Microoptimizations Using Tizen Code as an Example".


Popular related articles
PVS-Studio ROI

Date: Jan 30 2019

Author: Andrey Karpov

Occasionally, we're asked a question, what monetary value the company will receive from using PVS-Studio. We decided to draw up a response in the form of an article and provide tables, which will sho…
Characteristics of PVS-Studio Analyzer by the Example of EFL Core Libraries, 10-15% of False Positives

Date: Jul 31 2017

Author: Andrey Karpov

After I wrote quite a big article about the analysis of the Tizen OS code, I received a large number of questions concerning the percentage of false positives and the density of errors (how many erro…
How PVS-Studio Proved to Be More Attentive Than Three and a Half Programmers

Date: Oct 22 2018

Author: Andrey Karpov

Just like other static analyzers, PVS-Studio often produces false positives. What you are about to read is a short story where I'll tell you how PVS-Studio proved, just one more time, to be more atte…
Technologies used in the PVS-Studio code analyzer for finding bugs and potential vulnerabilities

Date: Nov 21 2018

Author: Andrey Karpov

A brief description of technologies used in the PVS-Studio tool, which let us effectively detect a large number of error patterns and potential vulnerabilities. The article describes the implementati…
The Last Line Effect

Date: May 31 2014

Author: Andrey Karpov

I have studied many errors caused by the use of the Copy-Paste method, and can assure you that programmers most often tend to make mistakes in the last fragment of a homogeneous code block. I have ne…
The Ultimate Question of Programming, Refactoring, and Everything

Date: Apr 14 2016

Author: Andrey Karpov

Yes, you've guessed correctly - the answer is "42". In this article you will find 42 recommendations about coding in C++ that can help a programmer avoid a lot of errors, save time and effort. The au…
The way static analyzers fight against false positives, and why they do it

Date: Mar 20 2017

Author: Andrey Karpov

In my previous article I wrote that I don't like the approach of evaluating the efficiency of static analyzers with the help of synthetic tests. In that article, I give the example of a code fragment…
PVS-Studio for Java

Date: Jan 17 2019

Author: Andrey Karpov

In the seventh version of the PVS-Studio static analyzer, we added support of the Java language. It's time for a brief story of how we've started making support of the Java language, how far we've co…
Static analysis as part of the development process in Unreal Engine

Date: Jun 27 2017

Author: Andrey Karpov

Unreal Engine continues to develop as new code is added and previously written code is changed. What is the inevitable consequence of ongoing development in a project? The emergence of new bugs in th…
The Evil within the Comparison Functions

Date: May 19 2017

Author: Andrey Karpov

Perhaps, readers remember my article titled "Last line effect". It describes a pattern I've once noticed: in most cases programmers make an error in the last line of similar text blocks. Now I want t…

Comments (0)

Next comments
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site.
Learn More →