Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve code readability while optimising

I am writing a scientific program in Python and C with some complex physical simulation algorithms. After implementing algorithm, I found that there are a lot of possible optimizations to improve performance. Common ones are precalculating values, getting calculations out of cycle, replacing simple matrix algorithms with more complex and other. But there arises a problem. Unoptimized algorithm is much slower, but its logic and connection with theory look much clearer and readable. Also, it's harder to extend and modify optimized algorithm.

So, the question is - what techniques should I use to keep readability while improving performance? Now I am trying to keep both fast and clear branches and develop them in parallel, but maybe there are better methods?

like image 440
user517893 Avatar asked Sep 04 '11 17:09

user517893


People also ask

What is more important to you readability of code or good performance of code and why *?

Correctness is the most important If your code is not correct at all, then it does not matter how readable or performant it is. There are some products where the whole system or part of it revolves around performance. In these cases, your product cannot be correct if it does not match the expected performance.

Why is readable code important?

Readable source code facilitates the reading and understanding of the abstraction phases and as a result, facilitates the evolution of the codebase. Readable code saves future developers' time and effort.

What is code readability?

Code readability is one of the first factors a developer learns, making it a quality one should always master. It merely means writing and presenting your code in such a manner that it can be easily read and understood. Much easier said than done, but it is as important as solving the problem.


Video Answer


1 Answers

Just as a general remark (I'm not too familiar with Python): I would suggest you make sure that you can easily exchange the slow parts of the 'reference implementation' with the 'optimized' parts (e.g., use something like the Strategy pattern).

This will allow you to cross-validate the results of the more sophisticated algorithms (to ensure you did not mess up the results), and will keep the overall structure of the simulation algorithm clear (separation of concerns). You can place the optimized algorithms into separate source files / folders / packages and document them separately, in as much detail as necessary.

Apart from this, try to avoid the usual traps: don't do premature optimization (check if it is actually worth it, e.g. with a profiler), and don't re-invent the wheel (look for available libraries).

like image 144
Roland Ewald Avatar answered Sep 29 '22 19:09

Roland Ewald