# Virtualization & performance

> How the grid renders only what is visible, how to use variable row heights, and what to do to keep a million rows fast.

Birch UI Grid renders only the rows and columns that are on screen, plus a small buffer. The cost of a render is proportional to the number of visible cells, not to the size of your dataset, so 100 rows and 1,000,000 rows scroll the same way.

**Live demo: 100,000 rows, virtualized** (runs on the HTML version of this page). Source of `demos/virtualization-100k.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createGrid, type ColumnDef } from '@birchui/core';
import {
  button,
  docsTheme,
  formatCurrency,
  layout,
  makeOrders,
  onDocsThemeChange,
  revenueOf,
  type Order,
} from './_shared';

export const meta = { title: '100,000 rows, virtualized', height: 480 };

const ROW_COUNT = 100_000;

const columns: ColumnDef<Order>[] = [
  { field: 'orderNo', header: '#', type: 'number', width: 90 },
  { field: 'id', header: 'Order', width: 120 },
  { field: 'customer', header: 'Customer', width: 200 },
  { field: 'country', header: 'Country', width: 150 },
  { field: 'region', header: 'Region', width: 140 },
  { field: 'product', header: 'Product', width: 200 },
  { field: 'category', header: 'Category', width: 130 },
  { field: 'rep', header: 'Sales rep', width: 160 },
  { field: 'quantity', header: 'Qty', type: 'number', width: 80 },
  { field: 'unitPrice', header: 'Unit price', type: 'number', width: 110, format: formatCurrency },
  { id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency },
  { field: 'status', header: 'Status', width: 110 },
  { field: 'orderDate', header: 'Ordered', type: 'date', width: 120 },
  { field: 'quarter', header: 'Quarter', width: 100 },
];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const started = performance.now();
  const rows = makeOrders(ROW_COUNT, 99);
  const grid = createGrid<Order>(body, {
    columns,
    rows,
    getRowId: (order) => order.id,
    defaultColumn: { sortable: true },
    theme: docsTheme(),
    ariaLabel: 'One hundred thousand orders',
  });
  const ready = performance.now() - started;
  status.textContent = `${ROW_COUNT.toLocaleString()} rows generated and rendered in ${Math.round(ready)} ms. Only visible rows and columns are in the DOM.`;
  toolbar.append(
    button('Jump to row 50,000', () => grid.scrollToRow(49_999, 'center')),
    button('Jump to last row', () => grid.scrollToRow(grid.getDisplayRows().length - 1, 'end')),
    button('Sort by revenue', () => {
      const t = performance.now();
      grid.setSort([{ colId: 'revenue', dir: 'desc' }]);
      status.textContent = `Sorted ${ROW_COUNT.toLocaleString()} rows in ${Math.round(performance.now() - t)} ms.`;
    }),
  );
  const offScroll = grid.on('viewportScroll', () => {
    const rendered = grid.getRenderedRows();
    if (!rendered.length) return;
    status.textContent = `Rows in the DOM: ${rendered.length} of ${ROW_COUNT.toLocaleString()}.`;
  });
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    offScroll();
    stopTheme();
    grid.destroy();
  };
}
```

## Row virtualization

The grid computes which display rows intersect the viewport, renders those plus `overscanRows` extra rows above and below, and recycles row elements as you scroll. Elements that leave the buffer are reused for rows that enter it, so scrolling creates almost no garbage.

```ts title="large-ledger.ts"
import { createGrid, type ColumnDef } from '@birchui/core';

interface LedgerEntry {
  id: number;
  posted: string;
  account: string;
  costCenter: string;
  description: string;
  debit: number;
  credit: number;
}

const accounts = ['4000 Revenue', '5000 COGS', '6100 Travel', '6200 Software', '6300 Facilities'];
const costCenters = ['Sales EMEA', 'Sales NA', 'Field Service', 'R&D', 'Finance'];

const entries: LedgerEntry[] = Array.from({ length: 1_000_000 }, (_, i) => ({
  id: i + 1,
  posted: new Date(Date.UTC(2026, 0, 1) + (i % 365) * 86_400_000).toISOString().slice(0, 10),
  account: accounts[i % accounts.length],
  costCenter: costCenters[(i * 7) % costCenters.length],
  description: `Journal ${100000 + i}`,
  debit: i % 2 ? Math.round((i % 9973) * 1.37 * 100) / 100 : 0,
  credit: i % 2 ? 0 : Math.round((i % 7919) * 2.11 * 100) / 100,
}));

const columns: ColumnDef<LedgerEntry>[] = [
  { field: 'id', header: 'Entry', type: 'number', width: 100 },
  { field: 'posted', type: 'date', width: 120 },
  { field: 'account', width: 160, filter: true },
  { field: 'costCenter', header: 'Cost center', width: 150, filter: true },
  { field: 'description', flex: 1, minWidth: 200 },
  { field: 'debit', type: 'number', width: 120 },
  { field: 'credit', type: 'number', width: 120 },
];

createGrid<LedgerEntry>(document.querySelector('#ledger')!, {
  columns,
  rows: entries,
  getRowId: (e) => String(e.id),
  rowHeight: 32,
  floatingFilters: true,
});
```

### Very tall grids

Browsers cap how tall a scrollable element can be. When the total height of all rows exceeds 10,000,000 pixels (about 312,000 rows at 32 pixels), the grid maps the scrollbar range onto the virtual height. Scrolling, `scrollToRow()` and keyboard navigation keep working exactly, and the scrollbar thumb simply covers more rows per pixel.

## Column virtualization

Unpinned columns are virtualized horizontally in the same way, with `overscanColumns` extra columns on each side. Pinned columns are always rendered. Wide grids with hundreds of columns, such as a pivot result or a monthly forecast, stay as fast as narrow ones.

## Overscan

| Option | Default | Meaning |
| --- | --- | --- |
| `overscanRows` | `6` | Extra rows rendered above and below the viewport. |
| `overscanColumns` | `2` | Extra unpinned columns rendered left and right of the viewport. |

A larger overscan reduces the chance of seeing blank space during very fast scrolling, at the cost of rendering more cells per frame. The defaults suit most grids; raise them slightly for grids with cheap cells and lower them for grids with expensive cell renderers.

```ts
createGrid(container, { columns, rows, overscanRows: 8, overscanColumns: 2 });
```

## Variable row heights

`rowHeight` can be a function of the display row:

```ts
createGrid<Ticket>(container, {
  columns,
  rows: tickets,
  rowHeight: (row) => {
    if (row.kind !== 'data' || !row.data) return 36;
    return row.data.notes.length > 120 ? 64 : 36;
  },
});
```

The grid calls the function once per display row whenever the row model changes, stores the offsets in a typed array, and finds the visible rows with a binary search while scrolling. That keeps variable heights fast even with a million rows, but the function itself runs a million times per data change, so keep it to simple arithmetic on the row.

Return a positive number of pixels. A function that throws or returns something else falls back to the density's row height for that row (34 pixels at the default density).

Uniform heights (`rowHeight: 32`) skip the offset table entirely and are the fastest option. Grid Pro rows that carry their own height, such as master/detail panels, switch the grid to the offset table automatically.

## Guidance for a million rows

The grid's own work is bounded by what is visible. What you put into it is not. These practices keep large grids responsive.

### Always set getRowId

Stable IDs let the grid preserve selection and focus across updates and match `applyTransaction` updates in a single pass. Use a primitive key that already exists on the row.

### Update with transactions, not setRows

`setRows()` re-indexes every row. `applyTransaction()` touches only what changed. For live data, batch changes once per animation frame as shown in [Updating data](https://docs.birchui.com/grid/updating-data.md#streaming-updates).

### Keep value getters cheap

`valueGetter` runs for every row when sorting or filtering by that column and for every visible cell when rendering. Avoid allocating objects, formatting dates or searching arrays inside it. Precompute derived fields when you load data:

```ts
const rows = raw.map((entry) => ({ ...entry, net: entry.debit - entry.credit }));

const columns: ColumnDef<LedgerEntry & { net: number }>[] = [{ field: 'net', type: 'number' }];
```

Reuse formatter instances instead of creating them per call:

```ts
const eur = new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' });

const columns: ColumnDef<LedgerEntry>[] = [
  { field: 'debit', type: 'number', format: (v) => (v ? eur.format(Number(v)) : '') },
];
```

### Keep cell renderers light

A `cell` renderer runs every time a cell scrolls into view. Return a string where you can, build small DOM trees, and never attach listeners to `document` from a renderer. For click handling across many cells, listen once to the grid's `cellClick` event instead of adding a listener per cell.

```ts
grid.on('cellClick', ({ colId, row }) => {
  if (colId === 'actions' && row) openEntry(row.id);
});
```

### Mind the quick filter on huge datasets

The quick filter builds one search string per row, from every column you defined including hidden ones, the first time it runs, and reuses it until the rows change. Wide grids with many hidden columns therefore pay for those columns too; leave purely technical fields out of `columns` if they should never be searched. The first keystroke on a million rows does the most work; debounce the input for very large datasets (the built-in floating filters already wait 200 ms):

```ts
let timer = 0;
search.addEventListener('input', () => {
  clearTimeout(timer);
  timer = window.setTimeout(() => grid.setQuickFilter(search.value), 150);
});
```

### Load data off the main thread

Parsing a large JSON payload can take longer than rendering it. Fetch and parse in a worker, then pass the array to the grid in one call.

## Measuring

`getRenderedRows()` returns the display rows that currently have DOM elements. It is useful in tests and when profiling:

```ts
grid.on('viewportScroll', () => {
  console.info('rendered rows', grid.getRenderedRows().length);
});
```

### Reference timings

The core package's performance tests enforce a budget for creating, sorting, filtering and scrolling 200,000 rows. Measured with 1,000,000 rows on a development machine under heavy load:

| Operation | Time |
| --- | --- |
| Sort by a numeric column | about 1.2 s |
| Filter | about 0.4 s |
| One scroll frame | under 3 ms |

Sorting and filtering scale with the number of rows; scrolling does not. Numeric, date and boolean columns without a custom comparator take a faster sort path than text columns or columns with a `comparator`.

## Related

- [Rows & row IDs](https://docs.birchui.com/grid/rows.md)
- [Updating data](https://docs.birchui.com/grid/updating-data.md)
- [Pagination](https://docs.birchui.com/grid/pagination.md) when you want pages for design reasons
