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 want to get future blog posts, make sure to follow me on social media.