Skip to content

Instantly share code, notes, and snippets.

@hzhou
Created August 21, 2015 15:50
Show Gist options
  • Save hzhou/1a117914a43f8f98c03a to your computer and use it in GitHub Desktop.
Save hzhou/1a117914a43f8f98c03a to your computer and use it in GitHub Desktop.
Literated Programming on Optimized Code

We often will write code in a way that optimize for the performance, in the meantime, sacrifices readability. In one example, we may insert low level tweaks such as inline assembly code. In another example, we may use some complicated algorithm to replace a simple one. L et's say in the code we need a sorting function, we may write a simple insertion code, but that performs poorly when the data size gets big. So we may use quick sort instead, but quick sort does not perform as well for small data set which often are the frequent use case s, and further, quick sort performs poorly when the data is already roughly in order. So to optimize, we need add certain pre-checking code and choose algorithm based on the checking result. Before long, we have several hundered lines of code to do sorting and they are a ll necessary -- but now the task of comprehending the program just expanded by several hundered lines and they are several hundered logic intensive code.

This is not desirable because the complicated sorting algorithm should not be in the way of comprehending the program, the program can be wrong with much simpler code. Also the dependency on the extra complication narrows one's freedom to experiment new idea.

I think the answer is to include both versions like following:

# main code
# $call sort_data_simple
$call sort_data_optimized

subcode: sort_data_simple
    # simple code
    ...

subcode: sort_data_complicated
    # very complicated
    # probably best to tuck in a separate file
    ...

Even though sort_data_simple is not used in production, the inclusion in the codebase makes the code much more readable and flexible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment