Code Optimization Tips With Examples
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.
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.
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.