Code Optimization Tips With Examples

ยท 268 words ยท 2 minute read

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 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 follow me on social media.

waffarx cash back