Code Optimization - The key to quality in code

Code Optimization - The key to quality in code

ยท

3 min read

As I advance as a jr. developer, I have been seeking ways to improve my coding skills. From a wide range of areas that such pursuit can lead us to, an excellent insight I gained is the importance of code optimization. In short, it is the process in which a system is improved to perform better, meaning lower processing time and use of resources, etc. In other words, code optimization makes better software.

To start with, programming languages are like any other language. An idea can be communicated in various forms. Let alone sound dimension, as in writing; there are many phrasal compositions to greet someone, for example. We can say "hello" or "hi" or even use an abbreviation in a way it can be understood; the same is true when we write for computers. As we code, there will be many ways to reach a solution, and there is no right or wrong here. However, there are metrics for code to be evaluated regarding the use of resources, speed and cohesion.

Regarding speed, code optimization focuses more specifically on the central processing unit(CPU). The CPU reads and executes the commands, but they are treated differently. An if statement stops the system's flow for a condition to be evaluated, making the processing slower. Nested ifs repeat the same for every evaluation, causing a loss in performance.

Moreover, another application of code optimization is algorithm efficiency measurement which regards resource usage. Also known as Big O Notation, there are notations to classify and evaluate the scalability of an algorithm relating to the input. Below are a few samples with their respective representation of time and input.

# big O(1)
function salut(name){
  print("Hello, ", name)
}

# big O(n)
function salut(nameArray){  
  for (let i = 0; i < nameArray.length; i++){
    print("Hello, ", nameArray[i])
  }
}

# big O(nยฒ)
function matrix(linesArray, columnsArray){  
  for (let i = 0; i < linesArray.length; i++){
    for (let j = 0; j < columnsArray.length; j++){
      print("Line: ", linesArray[i], " X Column: ", columnsArray[j])
    }
  }
}

image.png

As stated before, optimization is how a system improves to work more efficiently. For every idea we implement in code, there is a more straightforward way of expressing commands that will result in the desired behavior, and very often, it is how we write the less code possible. In light of that, it is essential to master the vocabulary of a language to apply all its possibilities to the best of code.

To sum up, code optimization allows a system to do its best. As the practices can be attributed to many scopes, it would require a very extensive article to cover all about the subject in detail. Still, if you are interested, you can find many more cases on Wikipedia's page on the subject.

ย