Value In Brief
All You Need To Know Explained In Brief

Code Optimization Tips With Examples

Code Optimization

In this post, I will show you how to optimize your code with examples. Optimization for speed, readability and scalability. Almost all code snippets will be written in Go programming languages, but still .. all those tips are applicable in other programming languages like PHP, Javascript, Java, Kotlin, .. etc.

Calculate it once

calculating things again and again is horrible. It consumes CPU time more than actually needed. So we should stop re-calculating things.

When we write a for loop, we compare the iterator against a number .. usually that number is an array length. Why we re-calculate the array length before each iteration/loop 🤨 we should calculate it ONCE , then re-use it in a variable.

The image shows the left code (non-optimized) and the right code (optimized) written in Go. This is applicable in all programming languages that have a for loop.

loop optimization

never re-calculate the length of array before each iteration of a for loop

No else in conditions (early return)

use the execution flow instead of if-else to simplify multiple checks in your code.

early return

use execution flow of code instead of else in if-else

N O T E, this post is not complete yet because I will add more tips for code optimization weekly—God Willing.

If you use Facebook, follow us on Value In Brief, Egyptian Coding Geeks, Egyptian Gopher or Software Pharaoh. All code optimization posts are included in one hashtag called #better_code.

You can follow me on Twitter and LinkedIn if you are there.

If you want to get future blog posts, make sure to subscribe to Value In Brief by Email.