The Fastest Code Starts by Refusing to Do Unnecessary Work
Hatched by Kai Nguyen
Aug 31, 2026
11 min read
2 views
91%
What if the deepest principle of performance has little to do with processors, databases, or clever algorithms?
A database query becomes fast when it avoids making the database examine, calculate, sort, and return things that do not matter. A Python module becomes understandable when it avoids forcing a reader to reconstruct what a function, attribute, or class means from scattered clues. In both cases, excellence comes from the same discipline: make the intended path easy to recognize, and make irrelevant paths expensive to enter.
This connection reveals a broader idea about software quality. Optimization is not merely the art of making machines work faster. It is the art of reducing unnecessary search, whether the search is performed by a query planner or by a human mind.
Two Kinds of Search, One Design Problem
A SQL query and a docstring seem to belong to different worlds. One manipulates tables and indexes. The other explains code to people. Yet both answer a similar question: how can a system locate the relevant meaning without inspecting everything?
Consider a database table containing ten million customer records. If a query asks for customers whose email address begins with alex, an index can often guide the database directly toward the relevant region. But if the query applies a transformation to the indexed value, such as wrapping the column in a function, or searches for a value with a leading wildcard, the database may lose that shortcut. It may need to inspect far more rows than the programmer intended.
Now consider a function with no documentation:
def calculate(x, y, z):
...
A reader cannot tell what the inputs represent, what the function returns, or what constraints apply. The reader must search through the implementation, trace callers, inspect tests, and infer intent. The code may execute efficiently, but the human interaction with it is poorly optimized.
A concise docstring acts like a human facing index:
def calculate(principal, annual_rate, years):
"""Return the future value of a fixed principal investment."""
...
The summary line does not explain every implementation detail. It performs a more valuable operation first: it lets the reader decide whether further investigation is necessary.
Good design narrows the search space before search begins.
This is the shared logic behind SARGABLE queries and useful documentation. A query is SARGABLE when its search condition is expressed in a form that allows an index to participate efficiently. Documentation is cognitively SARGABLE when its most important meaning is expressed in a form that allows a reader to orient themselves immediately.
The analogy is not that docstrings literally improve runtime performance. They improve the performance of understanding, maintenance, debugging, and reuse. Those are not secondary costs. In a mature codebase, they often dominate the total cost of ownership.
The Hidden Cost of Making Others Infer
Developers often treat documentation as an explanatory layer added after the real work is done. That view resembles writing a query that retrieves everything and then filtering the results in application code. It may produce the correct answer, but it makes the system perform unnecessary work.
The same thing happens when code omits a clear summary line and expects every reader to infer intent from implementation details. The reader must process names, control flow, data structures, edge cases, and historical context before finding the central fact that could have been stated in one sentence.
This is why the distinction between a one line docstring and a longer docstring matters. A one line form is appropriate when the purpose is obvious and can genuinely fit on one line. When the object needs more explanation, the structure should begin with a summary line, followed by a blank line, followed by the fuller description. This is not merely a stylistic preference. It is a progressive disclosure protocol.
The first line serves the quick scan. The rest serves the reader who has decided that the object deserves deeper attention. The format respects both audiences without making either audience pay the full cost.
SQL has a similar hierarchy. The database first identifies candidate rows, then applies conditions, then projects columns, then performs operations such as grouping or sorting. The closer a restriction can be applied to the data source, the less data must pass through later stages. Documentation also benefits from ordering information by decision value:
- What is this?
- What does it return or change?
- What assumptions or constraints matter?
- What details are needed for safe use?
A reader who only needs orientation can stop after the first answer. A reader who needs operational confidence can continue. The document has a shape that matches the economics of attention.
Indexes and Docstrings Are Both Contracts About Access
An index is not the data itself. It is a structure that makes certain forms of access cheap. Its usefulness depends on how the query is written. An index on a date column may be highly effective for a range condition, but far less useful if the column is transformed before comparison.
A docstring is also not the implementation itself. It is a structure that makes certain forms of access to the implementation cheap. It should expose the meaning most likely to be needed by a caller, maintainer, or tool. If it merely repeats the function name, it adds little. If it describes an obsolete behavior, it creates an access path to the wrong conclusion.
This suggests a practical test for documentation:
What question does this text make cheap to answer?
For a function, the answer might be, “Can I call this with a negative value?” For a class, it might be, “What state does this object own?” For an attribute, it might be, “Is this value derived, cached, or user supplied?” For a module, it might be, “What public capability does this package provide?”
The convention of attribute docstrings and additional docstrings is valuable because meaning does not live only inside functions. A module can have a string literal that explains its purpose. A class can clarify its role. An attribute can carry a nearby explanation of a subtle invariant. These forms acknowledge that software contains many surfaces where a reader may need orientation.
But adding more text is not automatically better. An enormous explanation at the wrong location can be as unhelpful as an unindexed table. The goal is not maximum documentation. The goal is highly located information.
A useful document is placed where the question arises. A useful index is placed where the query can exploit it. In both cases, structure determines whether information is available at the moment it matters.
SARGABLE Thinking for Human Readers
The database concept can become a general mental model for writing code and documentation. Before adding detail, ask whether the form of expression allows the intended consumer to use an existing shortcut.
For a database, this means avoiding unnecessary arithmetic or functions on indexed columns, being cautious with negation, avoiding leading wildcards where an index cannot help, choosing appropriate indexes, limiting result sizes, and filtering early. These practices all share one purpose: preserve the system's ability to eliminate irrelevant work quickly.
For human readers, the equivalents are surprisingly direct.
Avoid burying the purpose. If the reader must pass through ten lines of context before learning what a function does, the summary is too late.
Avoid disguising important constraints. A warning about accepted units, mutation, or exceptional cases should not be hidden in an unrelated paragraph.
Avoid vague transformations of meaning. Words such as “process,” “handle,” and “manage” often require the reader to inspect the implementation before they can form a useful hypothesis.
Avoid returning excessive information. A docstring that reproduces the entire function body in prose forces the reader to filter the explanation manually.
Use the right index. Names, section structure, summary lines, and consistent conventions are navigational structures. They help readers jump to the relevant meaning rather than scanning blindly.
The most important parallel is early filtering. In a code review, state the design constraint before presenting every implementation detail. In an API description, explain the result and side effects before listing internal mechanics. In a technical design, identify the decision being made before documenting every rejected alternative.
This is not an argument for simplistic writing. Complex systems require substantial explanation. It is an argument for putting the highest value information at the front of the path.
Clarity is not the removal of complexity. It is the placement of complexity where it can be handled deliberately.
The Query Planner in Your Head
When reading unfamiliar code, people behave like query planners. They form an initial estimate of where the answer might be, then choose a route through the available evidence. Clear names and summary lines improve that estimate. Consistent docstring conventions make the route predictable. Poor documentation causes repeated rescanning, just as a poorly shaped query can cause repeated table inspection.
This helps explain why a small documentation improvement can have an outsized effect. Suppose a function is called in thirty places. Without a clear contract, each maintainer may independently inspect its implementation, ask whether it mutates an argument, or guess what a return value means. One accurate summary can prevent dozens of searches. The benefit compounds with every caller and every future change.
The same compounding occurs with query design. A good index or a SARGABLE condition does not save work only once. It creates a reusable route that many executions can exploit. In both domains, the highest leverage improvements are those that change the default path for future users.
We can describe this with a simple model:
Total maintenance cost equals number of users multiplied by ambiguity multiplied by revisit frequency.
Documentation reduces ambiguity. Query structure reduces unnecessary data inspection. Both improve the default path rather than relying on exceptional effort from every individual consumer.
This also gives us a warning about conventions. A convention has value only when it supports a real retrieval need. Triple double quotes provide a consistent, tool friendly form. A summary line creates a predictable first stop. A blank line separates orientation from detail. These conventions are small, but their power comes from making the access pattern stable across an entire codebase.
Consistency is therefore not bureaucratic decoration. It is a form of indexing.
A Practical Method for Building Faster Understanding
When writing a query, begin by asking what data can be excluded earliest. When writing a docstring, ask what confusion can be prevented earliest. The workflow is nearly identical.
First, identify the primary retrieval question. For a query, it may be, “Which invoices remain unpaid this month?” For a function, it may be, “What does this return, and under what conditions?”
Second, express the filter in a form the consumer can exploit. In SQL, preserve index usability. In prose, use precise nouns, direct verbs, and a summary line that stands on its own.
Third, limit the result. Select only the columns needed. Explain only the behavior needed for safe use at that level of documentation. Additional detail should earn its place by answering a likely follow up question.
Fourth, inspect the plan. For a database, use query analysis tools and examine whether indexes are actually being used. For documentation, ask another developer to describe the function after reading only the first line. If they cannot, the summary is not yet doing enough work.
Finally, watch for accidental costs. Sorting and grouping may be unnecessary in a query. Repetition, stale claims, and implementation narration may be unnecessary in a docstring. The question is always the same: what work is the system doing because we failed to state the shape of the problem clearly?
Key Takeaways
-
Treat clarity as an optimization problem. Whether the consumer is a database engine or a human reader, good design reduces the amount of irrelevant material that must be examined.
-
Put the primary filter early. In SQL, filter rows as soon as practical. In documentation, state purpose, result, and critical constraints before secondary detail.
-
Write for progressive disclosure. Use a concise summary for quick orientation, then a blank line and a fuller explanation for readers who need more.
-
Build reusable access paths. Appropriate indexes, precise names, consistent docstrings, and well placed explanations reduce repeated investigation across future queries, callers, and maintainers.
-
Measure the cost of ambiguity. If every user must inspect the implementation to answer the same question, the system is paying repeatedly for missing structure.
The most efficient software is not software that performs the most operations elegantly. It is software that makes unnecessary operations difficult to trigger. That principle applies to disk reads, row scans, sorting, and computation. It also applies to interpretation.
A well designed query tells the database where to look. A well designed docstring tells the human reader what matters before they begin looking. Both are acts of respect for the consumer's limited attention.
Once you see documentation as a form of indexing, conventions such as summary lines, triple double quotes, and nearby attribute explanations stop looking cosmetic. They become part of the system's performance architecture. The machine runs faster when it searches less. The organization learns faster when its people search less.
The next time you optimize a query, ask not only whether the database can find the rows quickly. Ask whether the code around that query makes its purpose equally easy for a person to find. The fastest systems are often built by the same quiet decision: do not make the next mind, machine, or maintainer search for what you already know.
Sources
Hatch New Ideas with Glasp AI 🐣
Glasp AI allows you to hatch new ideas based on your curated content. Let's curate and create with Glasp AI :)
Start Hatching 🐣