Developers waste 97% of time worrying about the speed of the noncritical parts

blog-post-image

by Yasiru Amarathunga  |   August 29th, 2022

I've been thinking about this a lot.

Should I prioritize time complexity or readability when writing my code?

What works best?

Example:- Return an array with the highest and lowest number in the parameter

Method one is O(n log n):

                              function minMax(arr)

    arr.sort(function (a,b) {return a-b})

    return [arr[0], arr[arr.length - 1]]} // O(n log n)
                            

Method two is O(n):

                              function minMax(arr)

    let lowest, highest

    for (let i = 0; 0 < arr.length; arr++) { if (i < lowest) { lowest=i } if (i> highest) {

        highest = i

        }

        }

        return [lowest,highest]} // O(n)
                            

As you can see, the O(n) uses more lines and is less readable.

In DonaldKnuth's paper "StructuredProgrammingWithGoToStatements," he wrote: "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency have a strong negative impact when considering debugging and maintenance. 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%."

PrematureOptimization can be defined (in less loaded terms) as optimizing before we know that we need to.

A chicken and egg situation. It can become a never-ending argument if we misunderstand this.

Optimizing upfront without any need will be a waste of time. But when we feel we need to optimize, we might be too close to a significantly slower code.

We can use this PrematureOptimization as a risk mitigation strategy to push back to the faster code.

We should understand that we should not avoid using this strategy to come too close to the significantly slower code.

For those who work in an environment where there are no strict limitations for CPU cycle limits or Memory, you should not worry much about the optimization to the very end of faster code because it's a waste of time.

A general misconception is that optimized code is complicated. And optimization represents a trade-off. However, in practice, better-factored code often runs faster and uses less Memory.

Another misconception is that any level of execution speed, or resource usage, can be achieved once the code is complete. There are both practical and physical limits given any target platform; therefore, PrematureOptimization is not a solution but can help achieve performance.

I hope you all got an understanding of it.