# AdapTable Performance

Canonical page: https://www.adaptabletools.com/docs/dev-guide-support-adaptable-performance

- AdapTable is designed to work in even the most demanding data environments
- If a live Grid is slow, [profile](https://www.adaptabletools.com/docs/dev-guide-support-profiling/index.md) first, then apply the tips below
- The demos show AdapTable with 100,000 rows — with and without styles and ticking updates

If Support sees slowness, record a profile before changing configuration. The usual causes are listed under Performance Tips; the demos below are for reproducing load.

## Big Data

AdapTable is designed to work seamlessly with very large data sets.

- For grids with fewer than 100,000 rows we recommend using the Client-Side Row Model
- For larger grids the [Server-Side Row Model](https://www.adaptabletools.com/docs/dev-guide-row-models-server-overview/index.md) is required - also supported by AdapTable.

**Example: Displaying Big Data**

How AdapTable can handle very big data

- This demo loads **100,000** rows (and 20 columns)
- We have deliberately added very few styles or formats to allow you to add your own objects and test performance

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableOptions,
  CustomInFilterValuesContext,
  InFilterValueInfo,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Big Data',
  filterOptions: {
    customInFilterValues: (context: CustomInFilterValuesContext) => {
      // provide custom implementation for In filter to show count of each value
      let returnvalues = context.defaultValues
        .filter((info: InFilterValueInfo) => info)
        .map(info => {
          return {
            value: info.value,
            label: `${info.label} (${info.count})`,
          };
        });
      return {values: returnvalues};
    },
  },
  initialState: {
    Layout: {
      CurrentLayout: 'Table Layout',
      Layouts: [
        {
          Name: 'Table Layout',
          TableColumns: [
            'id',
            'prodName',
            'company',
            'price',
            'amount',
            'currency',
            'orderDate',
            'dueDate',
            'lastName',
            'firstName',
            'origin',
            'toAddress',
            'invoiceNum',
            'accountNum',
            'department',
          ],
          AutoSizeColumns: true,
        },
        {
          Name: 'Grouped Layout',
          TableColumns: [
            'id',
            'company',
            'price',
            'amount',
            'currency',
            'orderDate',
            'dueDate',
            'lastName',
            'firstName',
            'origin',
            'toAddress',
            'invoiceNum',
            'accountNum',
            'department',
          ],
          AutoSizeColumns: true,
          RowGroupedColumns: ['prodName'],
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';

export const onAdaptableReady = async ({adaptableApi}: AdaptableReadyInfo) => {
  const data = await fetchData();
  adaptableApi.gridApi.loadGridData(data);
  adaptableApi.columnApi.autosizeAllColumns();
};

const API_BASE = process.env.NEXT_PUBLIC_ORDERS_API_URL;
async function fetchData() {
  const response = await fetch(`${API_BASE}/100k`);
  return response.json();
}
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';

export const columnDefs: ColDef[] = [
  {
    field: 'id',
    cellDataType: 'number',
    hide: true,
    editable: false,
  },
  {
    field: 'prodName',
    headerName: 'Product Name',
    cellDataType: 'text',
    enableRowGroup: true,
  },
  {
    field: 'company',
    cellDataType: 'text',
    enableRowGroup: true,
  },
  {
    field: 'price',
    cellDataType: 'number',
  },

  {
    field: 'amount',
    cellDataType: 'number',
  },
  {
    field: 'currency',
    cellDataType: 'text',
    enableRowGroup: true,
  },

  {
    field: 'lastName',
    headerName: 'Customer Last Name',
    cellDataType: 'text',
    enableRowGroup: true,
  },
  {
    field: 'firstName',
    cellDataType: 'text',
    enableRowGroup: true,
  },
  {
    field: 'origin',
    headerName: 'Country of Origin',
    cellDataType: 'text',
    enableRowGroup: true,
  },
  {
    field: 'toAddress',
    headerName: 'Shipping Address',
    cellDataType: 'text',
  },
  {
    field: 'orderDate',
    cellDataType: 'date',
  },
  {
    field: 'dueDate',
    cellDataType: 'date',
  },
  {
    field: 'invoiceNum',
    headerName: 'Invoice Number',
    cellDataType: 'number',
  },
  {
    field: 'accountNum',
    headerName: 'Account Number',
    cellDataType: 'text',
  },
  {
    field: 'department',
    cellDataType: 'text',
    enableRowGroup: true,
  },
];
```

## Performance Tips

We leverage the excellent visualisation provided by AG Grid to ensure that styles are only applied to currently visible cells and rows.

Here a few tips to improve the performance of AdapTable:

- Use [Quick Search as Filter](https://www.adaptabletools.com/docs/handbook-quick-search-as-filter/index.md) very sparingly; but if used then look at leveraging AG Grid's [Quick Filter Cache](https://www.ag-grid.com/javascript-data-grid/filter-quick/#quick-filter-cache)
- Avoid using [Badge Styles](https://www.adaptabletools.com/docs/handbook-styled-column-badge/index.md) in cells which are updating regularly, and particularly if using [Flashing](https://www.adaptabletools.com/docs/handbook-flashing-cell/index.md)

## Performance Advisor Rules

The **Advisor** tab of [AdapTable DevTools](https://www.adaptabletools.com/docs/dev-guide-support-devtools/index.md) checks the live configuration against the rules below. Each finding links to its rule here.

The rules run in DevTools, so they add nothing to AdapTable. The facts they check are available to scripts and AI agents through `getPerformanceContext()` in the [DevTools in-page API](https://www.adaptabletools.com/docs/dev-guide-support-devtools-api/index.md)

Two rules use the Hot Paths results of a DevTools recording (with **Hot Paths** ticked) (re-filtering on data changes, IN filter values); the others read the current configuration

### Quick Search Filter Cache

[Quick Search as Filter](https://www.adaptabletools.com/docs/handbook-quick-search-as-filter/index.md) without AG Grid's [Quick Filter Cache](https://www.ag-grid.com/javascript-data-grid/filter-quick/#quick-filter-cache): every keystroke builds the searchable text of every row again (a warning above 10,000 rows). Set `cacheQuickFilter: true` in the AG Grid options, or set `quickSearchOptions.filterGridAfterQuickSearch` to false so Quick Search only highlights matches.

### Calculated Column Chains

[Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column-referencing/index.md) that reference each other 3 or more levels deep: each level evaluates the levels below it for every row. Turn on AG Grid's `valueCache`, or reference the underlying data columns directly.

### Calculated Column Value Cache

3 or more scalar [Calculated Columns](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md) without AG Grid's `valueCache`, when they reference each other or the Grid has 50,000+ rows: their values are computed again on every render, sort and filter.

### Badges on Flashing Columns

[Badge Styles](https://www.adaptabletools.com/docs/handbook-styled-column-badge/index.md) on columns with [Flashing Cells](https://www.adaptabletools.com/docs/handbook-flashing-cell/index.md): a Badge cell is rebuilt (its rules evaluated and a component mounted) on every change. Use a Format Column style for those columns, or remove the Flashing Cell definition from them.

### Data Change History Limit

[Data Change History](https://www.adaptabletools.com/docs/handbook-monitoring-data-change-history-configuring/index.md) without `maxDataChangesInStore` keeps every change, each holding a reference to its row: with ticking data the log, and the JS heap, grows for as long as the page is open (critical above 10,000 entries).

### Format Columns Scoped to All Columns

A [Format Column](https://www.adaptabletools.com/docs/handbook-column-formatting-conditions/index.md) with a Rule and Scope "All": the Rule is evaluated for every rendered cell of every visible column, on every scroll and refresh. Narrow the Scope to the columns that need it.

### Many Format Columns on One Column

More than 5 conditional [Format Columns](https://www.adaptabletools.com/docs/handbook-column-formatting-conditions/index.md) on one column: each rendered cell evaluates all of them. Combine rules that share a style, or move rarely used ones to a separate Layout.

### Invalid Expressions

An [Expression](https://www.adaptabletools.com/docs/adaptable-ql-expression/index.md) that cannot be evaluated is validated and logged again each time it is used, costing time on every evaluation and filling the console. Fix or delete it.

### Observable Expression History

[Observable](https://www.adaptabletools.com/docs/adaptable-ql-expression-observable/index.md) and Aggregation expressions keep a rolling history of changes in memory (a warning above 1,000,000 entries). Use the shortest `WITHIN()` windows that work, and lower `expressionOptions.maxHistoryPerCell` / `maxTimeframeSize` if you do not need long windows.

### Large Client-Side Grids

More than 100,000 rows in the Client-Side Row Model: sorting, filtering and grouping all run in the browser. Load only the rows the user needs, or move to the [Server-Side Row Model](https://www.adaptabletools.com/docs/dev-guide-row-models-server-overview/index.md) and let the server sort, filter and group.

### Autogenerated Primary Key

Without a unique data column AdapTable adds an id to each row (see [Primary Key](https://www.adaptabletools.com/docs/getting-started-primary-key/index.md)): updates can then only find rows by object identity, and reloaded data gets new ids, so Notes, Comments, Data Change History and row selection cannot follow rows across reloads. Set `primaryKey` to a column with unique values (or a composite you add to the data).

### Re-filtering on Data Changes

Measured by a recording with Hot Paths ticked: data changes triggering a full re-filter of the Grid at least once a second. AdapTable re-filters on every change while a Grid Filter is active, or when a changed column has a Column Filter (critical above 10,000 rows). Avoid Grid Filters and Column Filters on columns that tick, or batch updates (e.g. `api.gridApi.updateGridData` with several rows at once) so the Grid re-filters once per batch.

### Prepared Expression Cache

AdapTable turns each rule (Format Column conditions, Alert rules, Flashing Cell rules, Badge conditions, the Grid Filter) into a prepared evaluator the first time it runs, and keeps the 64 most recently used. With more distinct rules than that they keep pushing each other out: each one pushed out is parsed and prepared again when next needed, and an Observable rule can stop recording its change history meanwhile. Merge rules that apply the same style, and write a condition used in several places once, as a Named Query referenced with [QUERY()](https://www.adaptabletools.com/docs/adaptable-ql-expression-advanced-query-function/index.md).

### IN Filter Values

Measured by a recording with Hot Paths ticked: building an [IN filter](https://www.adaptabletools.com/docs/handbook-column-filter-in-filter/index.md)'s list reads the column in every row and counts its distinct values, when the filter is opened or shown and again after filters change or rows are added. On columns with many distinct values use a text or number filter, or provide `customInFilterValues` and return the values a page at a time (`hasMore`).

**Example: AdapTable Performance**

How AdapTable performs when lots is happening

- This demo also loads **100,000** rows (and 20 columns)
- The `Price` and `Amount` columns are updated **400 times per second**
- We have added a number of style-related elements to the Grid:
  - Custom [Flashing Cells](https://www.adaptabletools.com/docs/handbook-flashing-cell/index.md) to the ticking `Price` and `Amount` columns
  - A [Conditional Style](https://www.adaptabletools.com/docs/handbook-column-formatting-conditions/index.md) to the `Total Value` column (when > 80) - note that `Total Value` is a [Calculated Column](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md) and also **updates in real time**
  - A Row-based [Conditional Style](https://www.adaptabletools.com/docs/handbook-column-formatting-conditions/index.md) (Bold & Italic and Purple) where the `Product Name` is "Car" or "Bike"
  - A [Date Display Format](https://www.adaptabletools.com/docs/handbook-column-formatting-display-format-date/index.md) for the `Order Date` and `Due Date` columns
  - A [Percent Bar Style](https://www.adaptabletools.com/docs/handbook-styled-column-percent-bar/index.md) to the `Price Change` column
  - A [Badge Style](https://www.adaptabletools.com/docs/handbook-styled-column-badge/index.md) to `Product Name` column (with different style based on cell value)

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Performance',
  initialState: {
    Dashboard: {
      ModuleButtons: ['CalculatedColumn'],
    },
    Layout: {
      CurrentLayout: 'Table Layout',
      Layouts: [
        {
          Name: 'Table Layout',
          TableColumns: [
            'prodName',
            'company',
            'price',
            'priceChange',
            'amount',
            'total_value',
            'orderDate',
            'dueDate',
            'lastName',
            'firstName',
            'origin',
            'toAddress',
            'invoiceNum',
            'accountNum',
            'department',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-total_value',
          Scope: {
            ColumnIds: ['total_value'],
          },
          Rule: '[total_value] > 80',
          RowScope: {
            ExcludeSummaryRows: true,
          },
          Style: {
            BackColor: '#99ffff',
          },
        },
        {
          Name: 'style-all',
          Style: {
            FontWeight: 'Bold',
            FontStyle: 'Italic',
            ForeColor: 'var(--ab-color-palette-28)',
          },
          Scope: {
            All: true,
          },
          Rule: '[prodName] = "Car" OR [prodName] = "Bike"  ',
        },
        {
          Name: 'formatColumn-orderDate',
          Scope: {
            ColumnIds: ['orderDate', 'dueDate'],
          },
          DisplayFormat: {
            Formatter: 'DateFormatter',
            Options: {
              Pattern: 'MMM do yyyy',
            },
          },
        },
      ],
    },
    StyledColumn: {
      StyledColumns: [
        {
          Name: 'priceChange PercentBar',
          ColumnId: 'priceChange',
          PercentBarStyle: {
            RangeValueType: 'Number',
            CellRanges: [
              {
                Min: 0,
                Max: 30,
                Color: '#ff0000',
              },
              {
                Min: 30,
                Max: 50,
                Color: '#ffa500',
              },
              {
                Min: 50,
                Max: 200,
                Color: '#008000',
              },
            ],
          },
        },
        {
          Name: 'prodName Badge',
          ColumnId: 'prodName',
          BadgeStyle: {
            Badges: [
              {
                Rule: '[prodName] IN ("Car", "Bike")',
                PillStyle: {
                  BackColor: 'var(--ab-color-palette-23)',
                  ForeColor: 'var(--ab-color-palette-14)',
                },
              },
              {
                Rule: '[prodName] IN ("Hat", "Shoes", "Gloves", "Shirt", "Pants")',
                PillStyle: {
                  BackColor: 'var(--ab-color-palette-17)',
                  ForeColor: 'var(--ab-color-palette-14)',
                },
              },
              {
                PillStyle: {
                  BackColor: 'var(--ab-color-palette-28)',
                  ForeColor: 'var(--ab-color-palette-14)',
                },
                Rule: '[prodName] IN ("Fish", "Tuna")',
              },
              {
                PillStyle: {
                  BackColor: 'var(--ab-color-palette-19)',
                  ForeColor: 'var(--ab-color-palette-14)',
                },
                Rule: '[prodName] IN ("Computer", "Mouse", "Keyboard")',
              },
              {
                PillStyle: {
                  BackColor: 'var(--ab-color-palette-30)',
                  ForeColor: 'var(--ab-color-palette-14)',
                },
                Rule: '[prodName] IN ("Pizza", "Salad", "Cheese", "Sausages")',
              },

              {
                PillStyle: {
                  BackColor: 'var(--ab-color-palette-16)',
                  ForeColor: 'var(--ab-color-palette-14)',
                },
              },
            ],
          },
        },
      ],
    },
    FlashingCell: {
      FlashingCellDefinitions: [
        {
          Name: 'flashingCell-amount-anyChange',
          Scope: {
            ColumnIds: ['price', 'amount'],
          },
          Rule: 'ANY_CHANGE()',
          DownChangeStyle: {
            BackColor: '#ff7591',
          },
          UpChangeStyle: {
            BackColor: 'var(--ab-color-palette-20)',
          },
          NeutralChangeStyle: {
            BackColor: 'var(--ab-color-palette-15)',
          },
          FlashDuration: 300,
        },
      ],
    },
    CalculatedColumn: {
      CalculatedColumns: [
        {
          ColumnId: 'total_value',
          Expression: '[price] * [amount]',
          CalculatedColumnSettings: {
            DataType: 'number',
          },
          FriendlyName: 'Total Value',
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo, AdaptableApi} from '@adaptabletools/adaptable';
import {IRowNode} from 'ag-grid-enterprise';

export const onAdaptableReady = async ({adaptableApi}: AdaptableReadyInfo) => {
  const data = await fetchData();

  adaptableApi.gridApi.loadGridData(data);
  adaptableApi.columnApi.autosizeAllColumns();

  setTimeout(() => {
    randomlyUpdateData(adaptableApi);
  }, 1000);
};

const API_BASE = process.env.NEXT_PUBLIC_ORDERS_API_URL;
async function fetchData() {
  const response = await fetch(`${API_BASE}/100k`);
  const data = await response.json();
  return data.map((item: any) => ({...item, priceChange: 0}));
}

function randomlyUpdateData(api: AdaptableApi) {
  setInterval(() => {
    const visibleRows = api.agGridApi.getRenderedNodes();
    if (!visibleRows) {
      return;
    }

    const numberOfRowsToUpdate = 5;
    for (let i = 0; i < numberOfRowsToUpdate; i++) {
      const row = visibleRows[getRandomInt(-1, visibleRows.length - 1)];
      if (row) {
        updateRow(api, row);
      }
    }
  }, 30);
}

function getRandomInt(min: number, max: number) {
  return min + Math.ceil(Math.random() * (max + 1));
}

async function updateRow(api: AdaptableApi, row: IRowNode) {
  const getDelta = (num: number): number => Math.ceil(0.2 * num);
  const updateConfig = {runAsync: true};
  const initialData = row.data;
  if (!initialData) {
    return;
  }
  const priceDelta = getDelta(initialData?.price);
  const amountDelta = getDelta(initialData?.amount);
  const newPrice = initialData.price + getRandomInt(-priceDelta, priceDelta);
  const newAmount =
    initialData.amount + getRandomInt(-amountDelta, amountDelta);

  let newData = {
    ...initialData,
    price: newPrice,
    amount: newAmount,
    priceChange: getRandomInt(0, 100),
  };

  await api.gridApi.updateGridData([newData], updateConfig);
}
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';

export const columnDefs: ColDef[] = [
  {
    field: 'id',
    cellDataType: 'number',
    editable: false,
  },
  {
    field: 'prodName',
    headerName: 'Product Name',
    cellDataType: 'text',
  },
  {
    field: 'company',
    cellDataType: 'text',
  },
  {
    field: 'price',
    cellDataType: 'number',
  },
  {
    field: 'priceChange',
    cellDataType: 'number',
  },
  {
    field: 'initialPrice',
    cellDataType: 'number',
  },
  {
    field: 'amount',
    cellDataType: 'number',
  },
  {
    field: 'currency',
    cellDataType: 'text',
  },

  {
    field: 'lastName',
    headerName: 'Customer Last Name',
    cellDataType: 'text',
  },
  {
    field: 'firstName',
    cellDataType: 'text',
  },
  {
    field: 'origin',
    headerName: 'Country of Origin',
    cellDataType: 'text',
  },
  {
    field: 'toAddress',
    headerName: 'Shipping Address',
    cellDataType: 'text',
  },
  {
    field: 'orderDate',
    cellDataType: 'date',
  },
  {
    field: 'dueDate',
    cellDataType: 'date',
  },
  {
    field: 'orderDate',
    cellDataType: 'date',
  },
  {
    field: 'invoiceNum',
    headerName: 'Invoice Number',
    cellDataType: 'number',
  },
  {
    field: 'accountNum',
    headerName: 'Account Number',
    cellDataType: 'text',
  },
  {
    field: 'department',
    cellDataType: 'text',
  },
];
```
