Elegant coding Vs. computational complexity: the truth
As developer, is very frequent that you could incur into the most famous pursue of the glory: write elegant and beautiful code.
But what if elegant code is not performant code at all?
Let’s see two algorithms that actually achieve the same result: you have a list of integers, and for each index you want to find the product of every integer except the integer at that index (not using division!)
Here the elegant version:
As you can guess reading the code, or simply the name of the function, the code above
has a quadratic O(n^2)
complexity.
In fact, you can understand simply standing in front of the nested-loop.
Is that elegant? Yes, it is.
Now let’s see the ugly version:
As you can guess reading the code, or simply the name of the function,
the code above has a linear O(3n) == O(n)
complexity.
In fact, you can understand simply counting the 3 loop that aren’t nested each-other.
Is that ugly? Yes, it is.
but..
Lesson is: sometimes ugly (but performant!) is better :)