Write Inefficient Code

Published Feb 12, 2024
Revision: 1

While writing code I often catch myself prematurely optimizing it. In life taking action in a wasteful manner is quite shameful. In computer code however, this is hardly the case. Nobody is hurt by an extra iteration of an array at runtime in your code.

Ideas: it is important to recognize when performance truly matters. Most of the time is does not

In these cases where perf is less important we should value the inefficient but more readable or prettier code over the efficient but difficult to reason about code.

(fn alphanumeric_sort [identifiers]
  (var result (icollect [k v (pairs identifiers)]
      {:keys (id_to_list v) :id v }))
  (table.sort result an_compare)
result)

Here result is instantiated to collect a new list with my split identifiers from id_to_list. To make this optimization I have moved from operating on a list of strings or identifiers to a list of tables holding a list of identifier segments as well as the original id.

What is the alternative here? If I set aside my desire to create less arrays at runtime I can move the id to list conversion into my comparison function. This will create a new array in each comparison, of which there will be many more than there are items in the array.

(fn alphanumeric_sort [items]
  (table.sort items alphanumeric_compare)
result)

This code still runs plenty fast for sorting my files. Simplifying code at the cost of some invisible memory usage is often times worth it. You can afford to iterate over your data a few thousand times as long as your code is more coherent as a result.