iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🧠

Why You Should Not Sacrifice Semantics and Readability for Performance Alone

に公開
2025/09/05
3件

Sometimes I see designs that sacrifice semantics and readability solely for the sake of performance.
Such arguments sound plausible at first glance, but we need to calmly reconsider whether they are appropriate decisions in the long term.
This article explains the dangers of discarding readability and semantics for the sake of such "imperceptible optimizations."


1. React.Fragment vs div : The Illusion of Speed

React.Fragment(<></>) should not be used because it is worse in performance than div.

The Reality

  • The difference in execution speed between React.Fragment and div is imperceptible in most use cases.
  • Optimizations vary depending on React version and browser.

There was once talk that div is slightly faster. However, the difference is less than a few milliseconds and has almost no impact in real applications. Moreover, due to React's current optimizations, Fragment is considered faster. In other words, it is dangerous to base decisions on temporary differences in specific implementations or environments.

Reasons to Choose Fragment

React.Fragment has a clear intention: "I want to group elements but don't want to add anything to the DOM." Changing this to a div unnecessarily adds extra DOM nodes, which adversely affects CSS design and accessibility. If all you want is to group elements, use Fragment.

import { TextField } from './ui/TextField';

// ❌ Using div for performance reasons
function UserProfileField({ user }) {
  return (
    <div> {/* meaningless div */}
      <TextField label="Username" name={user.name} />
      <TextField label="Email Address" name={user.email} />
    </div>
  );
}

// ✅ Fragment with clear intent
function UserProfileField({ user }) {
  return (
    <> {/* Only for grouping field elements */}
      <TextField label="Username" name={user.name} />
      <TextField label="Email Address" name={user.email} />
    </>
  );
}

2. for Loop vs Generator Function: Are You Setting the Wrong Optimization Priorities?

Generator functions have better performance than for loops.

Is It Really Effective?

  • Generator functions have the advantage of memory efficiency through lazy evaluation, but for small amounts of data, there is almost no performance difference.
  • They should not be used at the cost of readability and maintainability.

Don't Optimize Without Inconvenience

Certainly, there are cases where Generator functions excel in loop processing. However, noticeable differences in execution time only occur when handling very large amounts of data.

Premature optimization is the root of all evil.

As the saying goes, performance improvement should wait until inconvenience actually occurs. Improvements that barely show a difference even when profiled are merely "unnoticed optimizations" and become technical debt by sacrificing readability.

// ❌ Example sacrificing readability for performance reasons
function* filterLargeCompletedOrders(orders: Iterable<Order>, limit: number): Generator<Order> {
  let count = 0
  for (const order of orders) {
    if (order.status !== 'completed') continue

    const taxExcluded = Math.round(order.amount / 1.1)
    if (taxExcluded <= 10_000) continue

    yield { ...order, amount: taxExcluded }

    count++
    if (count >= limit) return
  }
}

// ✅ Example prioritizing readability and simplicity (limit = 100)
function processOrderData(orders: Order[], limit: number): Order[] {
  return orders
    .filter(order => order.status === 'completed')
    .map(order => ({
      ...order,
      amount: Math.round(order.amount / 1.1)
    }))
    .filter(order => order.amount > 10_000)
    .slice(0, limit);
}

3. Should We Really Stop Using Barrel Exports?

Barrel exports that re-export from index.ts should be avoided because they negatively impact performance.

Behind this claim are concerns about inefficient tree-shaking and runtime module resolution overhead. However, when we calmly examine it, those concerns alone are not enough reason to abandon barrel exports.

Is Runtime Overhead Really Serious?

Yes, there are cases where barrel exports cause all modules to be evaluated at once (e.g., when static resolution is not possible). However, the overhead is negligible in normal-sized applications, and unless a clear problem arises, there is no reason to avoid them.

If there is noticeable overhead, the cause is not barrel exports. The problem likely lies in tight coupling of module dependency structures or initialization processes.

The Advantages of Readability and Structural Clarity Are Overwhelming

The biggest advantage of barrel exports is that imports are consolidated in one place, making structure and dependencies clear.

  • By aggregating imports, a quick glance at the top of the file reveals which modules are depended on
  • Compared to individually importing from multiple files, import statements become more concise and organized, reducing noise and improving readability.

This is particularly effective for maintaining intended groupings in domain- or layer-based designs, and also contributes to maintainability during team development and refactoring.

// ❌ Example with scattered individual imports
// usecases/CreateUserUseCase.ts
import { ValidationComponent } from '../components/validation/ValidationComponent';
import { NotificationComponent } from '../components/notification/NotificationComponent';
import { LoggingComponent } from '../components/logging/LoggingComponent';
import { CacheComponent } from '../components/cache/CacheComponent';
import { UserService } from '../services/UserService';
import { EmailService } from '../services/EmailService';
import { AuditService } from '../services/AuditService';

// ✅ Clear structure with barrel export
// usecases/CreateUserUseCase.ts
import { ValidationComponent, NotificationComponent, LoggingComponent, CacheComponent } from '../components';
import { UserService, EmailService, AuditService } from '../services';

Tree-Shaking Concerns Are a Thing of the Past

There is also talk that "barrel exports are disadvantageous for tree-shaking", but this is from the era when old bundlers and CJS modules were mainstream.

  • Modern bundlers (Vite, ESBuild, webpack5 and later) perform static analysis based on ESM and can remove unused exports
  • If TypeScript and ESM are used correctly, situations where tree-shaking does not work are almost nonexistent.

Therefore, avoiding barrel exports mainly due to this concern is technically outdated.

4. Should We Avoid Memoization Because of Overhead?

useMemo should only be used when performance is a concern.

This perspective only sees half of useMemo's role. useMemo is not only for performance optimization; it also has a semantic role of indicating that a value is a "derived value".

useMemo as a Declaration of a Derived Value

useMemo explicitly indicates in the code that a value is derived data computed from props or state. Not using it means the ambiguity of whether the value is "a temporary variable created anew each time" or "a value that should always yield the same result from specific inputs".

Omitting useMemo for performance reasons removes this important "derived value" meaning from the code, potentially causing misunderstandings when other developers handle that value. For example, if a value that should not need recalculation when props are the same is implemented without useMemo, a new instance is created every time, which can cause unintended re-renders.

useMemo for Conveying Meaning

Using useMemo clarifies which state or props the value depends on through the dependency array []. This makes the data flow within the component easier to follow, improving readability and maintainability.

// ❌ Example where it's unclear that the value is derived
function ItemSearch({ items }: { items: string[] }) {
  const [query, setQuery] = useState('');

  // Filtering runs every time query changes
  // It's hard to read that `filteredItems` is a derived value from `query` and `items`
  const filteredItems = items.filter(item => item.toLowerCase().includes(query.toLowerCase()));

  return (
    <>
      <input type="search" value={query} onChange={e => setQuery(e.target.value)} />
      <ul>
        {filteredItems.map(item => <li key={item}>{item}</li>)}
      </ul>
    </>
  );
}

// ✅ Explicitly indicating derived value with useMemo
function ItemSearch({ items }: { items: string[] }) {
  const [query, setQuery] = useState('');

  // Explicitly stating it's a value derived from `query` and `items`
  // The dependency array makes it clear when recalculation occurs
  const filteredItems = useMemo(() => {
    return items.filter(item => item.toLowerCase().includes(query.toLowerCase()));
  }, [items, query]);

  return (
    <>
      <input type="search" value={query} onChange={e => setQuery(e.target.value)} />
      <ul>
        {filteredItems.map(item => <li key={item}>{item}</li>)}
      </ul>
    </>
  );
}

useMemo is not a "magic incantation to add when performance gets bad." It is a fundamental tool for semantically correct expression of the ordinary process of "computing values from props or state." Performance benefits should be considered a side effect of this.

Reference Article

https://qiita.com/uhyo/items/59124425ca1dee3da891


Readability and Performance Are Not a Trade-off, but They Can Sometimes Conflict

This article has stated that "we should not sacrifice semantics and readability for performance," but this does not mean that "clean code is always best" in every case. In situations where performance improvements are required, we may have to adopt non-intuitive code.

The following article introduces examples of solving performance issues that actually negatively affect the user experience.

https://speakerdeck.com/koukimiura/hurontoendonopahuomansutiyuningu

  • If the increase in code complexity is limited, supplement the meaning with comments or utility functions
  • Allow active restructuring only when the performance effect can be clearly quantified
  • Domain logic and common processing have high readability priority, so maintain them as much as possible

In practice, it's important to strike such a balance.


Summary

  • Sacrificing semantics and readability for temporary, limited performance differences is putting the cart before the horse
  • React.Fragment, Generator functions, barrel exports, etc., should prioritize design intent over performance
  • Performance optimization is sufficient after the problem becomes apparent
  • Let's write meaningful code for our future selves
GitHubで編集を提案

Discussion

Honey32Honey32
  • ui/ : 「パッケージ」的じゃないので、index.ts 不要
    • card/ : 「パッケージ」的なので、index.ts を使って良い
      • index.ts
      • card.ts
    // 🔴 DON'T
    import { Button, Card, Modal } from "#/ui";
    
    // ✅️ DO
    import { Card } from "#/ui/card";
    
  • features/books/details : 書籍詳細ページ。「パッケージ的」index.ts が適している。
    • index.ts : バレル
    #/app/books/[bookId]/page.tsx
    import { BookDetailsPage } from "#/features/books/details"
    

個人的に、barrel export は、「カプセル化のためのパッケージ」としてのディレクトリに用意するのは問題ないですが、

そうでないようなディレクトリについては、用意する必要がない、むしろ、以下のような パフォーマンスではなく可読性の観点での デメリットがあるから避けたほうが良いと思います。

  • 無駄にコードジャンプが増える
  • ツリーシェイキングが失敗するかどうか気にするのが億劫

このように、ファイル間の依存関係を無用に複雑することは、バンドル時の依存解決のしくみに則っている RSC とは相性が悪く、保守性を著しく下げる原因になると思います。

実際に、それによってトラブルシューティングしあぐねている方に出会ったことがあります。 https://qiita.com/kay-adamof/items/8d7324810dd1b051d373

3
じょうげんじょうげん

ご意見ありがとうございます。
本論の意図としては、パフォーマンス面を理由にやらないのは間違いというものであり、barrel exportを全面的に採用すべきかどうかは議論の余地があると考えていました。

パッケージ的か、そうでないかでやるべきか判断が分かれるというのはその通りで、その都度判断するのが難しいという理由でしないというのは意味のある判断だと私も思います。

RSCを採用しているプロジェクトにおいても、clientとserverが入り乱れるようなモジュールがあるとしたら、それはbarrel exportを避けた方が良さそうですね。

4
Honey32Honey32

たしかに、本文を見返しましたが、そうですね!

(関係ないですが、「パッケージ的じゃないならバレルを使わない」ことについても、どこかにまとめておかないと…)

4