Answer the question
In order to leave comments, you need to log in
Clarity vs Optimality - Which is better?
How to write algorithms better: understandable or optimal.
Example, task - flip an array of integers. Clear approach: create a new array, run through the original array from the end, filling the new one. The optimal approach is to run the array to the middle, swapping the extreme elements (0<->N-1;1<->N-2...), and there you can also do the exchange not through a variable, but by subtraction / addition.
PS When optimization is needed, the choice is obvious. The question is about the general case when a program is written that does not wait for terabytes of data at the input.
Answer the question
In order to leave comments, you need to log in
When they say "optimal" I ask "by what criterion". Because running around the array to the middle is optimal in terms of memory, but it’s not a fact that the compiler will be able to correctly adjust reading and writing to the width of the cache lines.
And about the fact that the exchange through xor or addition-subtraction is better - the legend has been stretching since the days of machines where there was no xchg instruction and this trick made it possible to swap two registers without using the third one.
The "comprehensibility" of the code is just another criterion for optimality, and when to choose which one depends on the corporate standard for writing code.
This is not good. Both ways of dealing with an array are trivial. This is about how to say: here is the letter O , it is written trivially, but the letter Zh is aerobatics! What letter to choose for writing "War and Peace" and other optimal masterpieces?
Take your time with masterpieces, deal with the letters first.
such low-level tasks are usually solved by language methods/functions. if there are none (which is extremely rare), then it is better to make them optimal, the comment (docBlock) is responsible for the clarity of the path
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question