During the transition from writing code for the University assignments to writing real world softwares, I had to unlearn many things and learn to not overuse low level optimisations where it was not required. I had a big exposure to compiler optimisations at my University.
I am going to share a couple of “optimisations” to avoid that I see newbies often do, and I won't deny that I haven't done them myself (and still do). I have that in quotes because they are not really optimisations when all factors considered. I will follow up with more blog posts when I have more patterns to share.
As I work mostly on Go, some terms that I use will be Go specific (for example
"Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%." — Donald Knuth
1. Not breaking a function into smaller logical functions
...to avoid more function calls and maximum reuse of variables; at least that’s what I thought of when I used to keep a big function .
While calling many different methods is a performance overhead in terms of copying of function arguments and machine instruction indirection which might lead to cache misses, it is often too tiny to even notice. Smaller isolated logic is easier to understand, saves time in reviews and debugging, and easier to make changes.
2. Using globals when not necessary
I still remember the time when I used globals to “efficiently” pass data between functions during one of my internships and my manager was visibly annoyed. Fix was to pass those globals as function arguments from the origin.
While it might seem that globals simplify your code, when used incorrectly, it can often bring a lot of problems (especially when the package is used in more than one place) and make it hard to understand the behaviour. Use globals only for constants and for config variables in rare cases which cannot be passed in other ways.
If the function argument to be passed is large, then pass it as a reference (with proper care to not change the data where not intended).
3. Don’t spend a lot of time optimising
This one is repeating the above quote which I came across midway writing this blog post: don’t spend a lot of time optimising the code which is not on the hot path and that is not run often. Focus on readability and evolvability. The time spent on such optimisations often negates the benefits (if any).
Keep it simple. It is usually the case that someone else is going to touch (and also maintain) the code that you wrote. That's one of the biggest lessons I've learnt since I started "real world" coding where you often collaborate.