The Hidden Performance Cost of Ambiguity
Hatched by Kai Nguyen
Sep 05, 2026
10 min read
0 views
91%
What if the fastest database query and the clearest Python function are solving the same problem?
At first, SQL optimization and docstring conventions appear to belong to different worlds. One concerns indexes, execution plans, and the cost of scanning rows. The other concerns quotation marks, summary lines, and how programmers explain code. Yet both are responses to a deeper engineering problem: how can a system find the right meaning with the least unnecessary work?
A database query is interpreted by a planner. A function is interpreted by a programmer, a tool, or a future version of yourself. In both cases, ambiguity creates friction. It forces the interpreter to inspect more possibilities, perform more transformations, or hold more context before it can act.
The practical lesson is larger than either SQL tuning or documentation style. Good engineering makes intent easy to locate, easy to verify, and cheap to act upon. Performance is not only about faster machines. It is also about reducing the search required to understand what something means.
Every Interpreter Pays for Unclear Intent
Imagine a librarian asked to find every book about climate policy published after 2015. One request gives the librarian a precise classification, a date range, and a subject. Another says, “Find books that are probably relevant, except perhaps the older ones, and ignore anything that seems too technical.” The second request may eventually produce a useful pile, but it requires more judgment and more inspection.
A database optimizer faces an analogous choice. Consider a simple indexed column:
SELECT *
FROM orders
WHERE created_at >= '2026-01-01';
The condition is SARGABLE, meaning the search argument can be used efficiently by an index. The database can navigate directly toward the relevant portion of the data instead of examining every row. The structure of the expression exposes the question in a form the system can act on.
Now consider a less direct version:
SELECT *
FROM orders
WHERE YEAR(created_at) = 2026;
The human intention is similar, but the computational shape is different. The database may need to calculate the year for many values before it can decide which rows qualify. The indexed value has been wrapped in a function, making the path to the answer less direct.
This distinction has a close parallel in code documentation. A docstring that begins with a clear summary tells a reader what a function does before asking them to understand every implementation detail. A docstring that starts with historical context, caveats, and internal mechanics makes the reader perform the equivalent of a table scan.
The common principle is semantic locality: put the information needed for the next decision in the place where the interpreter will look first.
The best interface is not merely correct. It presents the truth in the form that its interpreter can use most cheaply.
For a query planner, that may mean leaving an indexed column exposed. For a programmer, it may mean placing a concise summary on the first line of a docstring. In both cases, the surface form is not cosmetic. It influences the cost of understanding.
Searchability Is a Form of Design
An index is valuable because it changes the search strategy. Without one, a database may inspect rows one by one. With one, it can jump through an organized structure. The data has not changed, but the route to the data has.
Documentation has its own indexes, although they are usually invisible. Readers scan the first line of a function description. Editors display docstrings in completion panels. Documentation generators extract summary text. Search engines and code search tools use predictable structure to locate concepts. A well formed docstring creates a small index for human attention.
This is why a one line docstring is appropriate for an obvious case. It answers the immediate question without making the reader traverse unnecessary structure:
def is_expired(token):
"""Return whether token is expired."""
The summary is compact because the function's contract is compact. For a more complex function, the same principle scales into a layered structure:
def calculate_discount(order, customer):
"""Calculate the discount for an order.
Apply the customer tier discount, then enforce the maximum discount
allowed for the order category. Return the final percentage as a decimal.
"""
The first line acts like a searchable key. The expanded description supplies the reasoning and constraints only when they are needed. This is not merely a stylistic preference. It is a deliberate arrangement of information by retrieval priority.
SQL has an equivalent layering. A WHERE clause narrows the population before later operations such as sorting, grouping, or projection. If a query filters late, it may carry irrelevant rows through expensive stages. If documentation explains the main contract only after several paragraphs of background, the reader carries irrelevant uncertainty through every sentence.
In both situations, early reduction matters. Reduce the rows before sorting them. Reduce the reader's uncertainty before explaining the exceptions.
This gives us a useful model for technical communication and system design:
- Identify the first decision the interpreter must make.
- Put the information required for that decision in an accessible form.
- Delay expensive transformation until the candidate set is small.
- Preserve detail for cases where detail is actually needed.
The model applies to query plans, APIs, documentation, dashboards, command line tools, and even organizational processes. Whenever a person or machine must search through possibilities, structure determines cost.
The Tax of Transformations
Many performance mistakes arise because developers transform data before asking a question. They perform arithmetic on an indexed column, apply a function, use a leading wildcard, or introduce a negation that makes direct navigation harder. The expression may be logically valid while still being operationally expensive.
The same mistake appears in explanations. A writer may begin with metaphor, implementation history, internal dependencies, or a list of exceptions before stating the basic purpose. These additions may be accurate, but they transform the reader's route to the central idea.
Consider these two descriptions:
def normalize_email(value):
"""Normalize an email address."""
And:
def normalize_email(value):
"""Perform a canonicalization procedure over user supplied address data.
This operation exists because several upstream systems historically emitted
inconsistent representations, and downstream comparison behavior varies by
storage layer and provider.
"""
The second version may contain useful context, but it postpones the most important fact. A reader looking for the function's purpose must decode terminology before receiving the answer. The function's behavior is hidden behind a transformation of language.
The issue is not verbosity by itself. Long explanations can be excellent. The issue is whether detail is placed after orientation. A useful long docstring gives the reader a stable point of reference, then expands into edge cases, assumptions, and examples. It does not force every reader to process every layer at once.
SQL optimization makes the same distinction between an expression that is logically equivalent and one that is execution friendly. Suppose a query needs records from the last thirty days. This form may prevent efficient use of an index:
WHERE DATEDIFF(day, created_at, CURRENT_DATE) < 30
A range condition states the boundary more directly:
WHERE created_at >= CURRENT_DATE - INTERVAL '30 days'
The exact syntax varies across database systems, but the design idea is stable. Put the transformation on the constant or boundary when possible, not on the indexed field. Let the system compare stored values using the structure it already has.
Documentation benefits from the same discipline. Put explanation around the concept, not between the reader and the concept. Do not make the reader reconstruct a simple contract from a transformed version of it.
This suggests a broader rule:
Transformations are not free. They cost computation in machines and interpretation in minds.
That cost is justified when it creates value. It is wasteful when it merely obscures a question that could have been stated directly.
The Contract Should Come Before the Machinery
A query is easier to optimize when its desired result is expressed clearly: which rows, under what conditions, in what order, and with what limits. A function is easier to use when its contract is equally visible: what it accepts, what it returns, what it changes, and which constraints matter.
This is why a docstring's summary line is more important than a decorative paragraph. It declares the contract before discussing the machinery. The reader can then decide whether to continue. If the function is not relevant, the summary has saved time. If it is relevant, the later details have a context in which to fit.
A well designed query follows a similar contract hierarchy:
- Filter the relevant records.
- Select only the needed columns.
- Limit the result when a limit is part of the request.
- Avoid unnecessary sorting and grouping.
- Use indexes that support the actual access pattern.
These choices are not isolated tricks. They all reduce the distance between intention and execution. They prevent the system from producing, carrying, or explaining information that nobody needs.
A common anti pattern in software is to confuse completeness with usefulness. Returning every column is treated as safer than selecting the required ones. Including every historical detail in a docstring is treated as more responsible than writing a concise contract. But excess information can weaken an interface by increasing the number of things the consumer must inspect.
The right goal is not minimalism for its own sake. It is progressive disclosure. Present the high value, high frequency information first. Make deeper information available without forcing it into the first decision.
This also explains why predictable conventions matter. Triple double quotes are not the source of clarity by themselves. Their value comes from making documentation recognizable to tools and readers. A consistent opening summary gives every function a familiar entry point, just as a consistent indexed condition gives a database a familiar route into its data.
Conventions become powerful when they align human expectations with machine behavior.
A Practical Framework for Lowering Interpretation Cost
The connection between query optimization and documentation can become a repeatable review method. Before shipping a query or a public function, ask four questions.
1. What is the first search?
For a query, is the database looking for a narrow range or scanning a broad population? For a function, is the reader immediately able to discover its purpose?
If the answer is no, expose the primary condition earlier. Rewrite the predicate. Add the summary line. Remove introductory material that delays orientation.
2. What is being transformed too soon?
Look for arithmetic, functions, negation, or leading wildcards applied to indexed columns. In prose, look for abstractions, background, and qualifications placed before the basic contract.
Ask whether the transformation is necessary at the point where it appears. If not, move it later or apply it to the boundary rather than the searchable value.
3. What unnecessary material is being carried forward?
A query may sort thousands of rows that could have been filtered earlier. A function description may explain internal details to readers who only need the return value.
Reduce the working set. Select fewer columns. State the common case first. Keep rare edge cases available, but do not make them the entrance.
4. Can the next interpreter verify intent quickly?
A database tool can reveal an execution plan. A reader can inspect a summary line and signature. In both cases, good design makes the path observable.
If a query performs poorly, use measurement rather than intuition. If a function is repeatedly misunderstood, improve the contract rather than blaming the reader. Performance problems and comprehension problems often reveal the same underlying defect: intent is present, but badly exposed.
Key Takeaways
- Treat clarity as an optimization problem. Every unnecessary scan, transformation, or explanation increases the cost of reaching the useful answer.
- Expose searchable intent early. Keep indexed columns in forms that support direct lookup, and put a function's summary on its first line.
- Filter before expanding. Reduce database rows before sorting or grouping, and reduce reader uncertainty before adding detailed context.
- Separate the contract from the machinery. State what a query returns or a function does before explaining how it works.
- Use conventions as access paths. Predictable query structure and predictable docstring structure help both machines and humans navigate faster.
The deepest lesson is that optimization is not only the art of making operations faster. It is the art of making the desired operation obvious.
A database does not become intelligent because it has an index. It becomes efficient because the query gives that index a usable question. A codebase does not become understandable because it contains many comments. It becomes understandable when its explanations present the right information at the moment a reader needs it.
Good design narrows the search space before asking anyone, or anything, to think harder.
Once you see this, documentation stops looking like an accessory to implementation. It becomes part of the system's access strategy. A docstring is an index into behavior. A query predicate is a sentence addressed to an execution planner. Both succeed when they preserve intent in a form that can be found and acted upon directly.
The fastest path through a system is often not a more powerful engine. It is a clearer question.
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 🐣