性能优化 #

一、渲染优化 #

1.1 使用正确的列表渲染 #

tsx
// 推荐:使用 For 组件
<For each={items()}>
  {(item) => <Item data={item} />}
</For>

// 避免:使用 map(每次重新创建)
{items().map(item => <Item data={item} />)}

1.2 条件渲染优化 #

tsx
// 推荐:使用 Show(保持 DOM 状态)
<Show when={visible()}>
  <ExpensiveComponent />
</Show>

// 避免:三元表达式(每次重新创建)
{visible() ? <ExpensiveComponent /> : null}

1.3 使用 createMemo 缓存计算 #

tsx
// 推荐:缓存昂贵计算
const sortedItems = createMemo(() => {
  return [...items()].sort((a, b) => a.name.localeCompare(b.name));
});

二、代码分割 #

2.1 懒加载组件 #

tsx
import { lazy } from 'solid-js';

const HeavyComponent = lazy(() => import('./HeavyComponent'));

function App() {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      <HeavyComponent />
    </Suspense>
  );
}

三、列表优化 #

3.1 虚拟列表 #

对于大型列表使用虚拟滚动:

tsx
import { createVirtualizer } from '@tanstack/solid-virtual';

function VirtualList() {
  const parentRef = createRef();

  const virtualizer = createVirtualizer({
    count: 10000,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 35
  });

  return (
    <div ref={parentRef} style={{ height: '400px', overflow: 'auto' }}>
      {/* 虚拟列表实现 */}
    </div>
  );
}

四、最佳实践总结 #

优化项 方法
列表渲染 使用 For 组件
条件渲染 使用 Show 组件
计算缓存 使用 createMemo
代码分割 使用 lazy 和 Suspense
大型列表 使用虚拟滚动
状态更新 使用 batch 批量更新

五、总结 #

  1. 使用 For 和 Show 进行高效渲染
  2. 使用 createMemo 缓存计算
  3. 懒加载大型组件
  4. 虚拟滚动处理大型列表
  5. 使用 DevTools 监控性能
最后更新:2026-03-28