Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions src/Body/MeasureCell.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
import * as React from 'react';
import ResizeObserver from 'rc-resize-observer';
import useLayoutEffect from 'rc-util/lib/hooks/useLayoutEffect';
import type { ColumnType } from '../interface';

export interface MeasureCellProps {
columnKey: React.Key;
onColumnResize: (key: React.Key, width: number) => void;
column?: ColumnType<any>;
prefixCls: string;
title?: React.ReactNode;
}

export default function MeasureCell({
columnKey,
onColumnResize,
column,
prefixCls,
title,
}: MeasureCellProps) {
const cellRef = React.useRef<HTMLTableCellElement>();

Expand All @@ -27,7 +26,7 @@ export default function MeasureCell({
return (
<ResizeObserver data={columnKey}>
<th ref={cellRef} className={`${prefixCls}-measure-cell`}>
<div className={`${prefixCls}-measure-cell-content`}>{column?.title || '\xa0'}</div>
<div className={`${prefixCls}-measure-cell-content`}>{title || '\xa0'}</div>
</th>
</ResizeObserver>
);
Expand Down
6 changes: 5 additions & 1 deletion src/Body/MeasureRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,17 @@ export default function MeasureRow({
>
{columnsKey.map(columnKey => {
const column = columns.find(col => col.key === columnKey);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using Array.prototype.find inside a map results in an O(N*M) time complexity, where N is the length of columnsKey and M is the length of columns. This can lead to performance degradation on tables with a large number of columns.

For better performance, you could create a lookup map from the columns array before iterating. This would reduce the complexity of finding a column to O(1) inside the loop.

You can achieve this by creating a memoized map at the top level of your component, like so:

const columnsMap = React.useMemo(() => {
  const map = new Map<React.Key, (typeof columns)[number]>();
  for (const col of columns) {
    if (col.key) {
      map.set(col.key, col);
    }
  }
  return map;
}, [columns]);

Then, inside your map function, you can retrieve the column efficiently:

const column = columnsMap.get(columnKey);

const rawTitle = column?.title;
const titleForMeasure = React.isValidElement<React.RefAttributes<any>>(rawTitle)
? React.cloneElement(rawTitle, { ref: null })
: rawTitle;
return (
<MeasureCell
prefixCls={prefixCls}
key={columnKey}
columnKey={columnKey}
onColumnResize={onColumnResize}
column={column}
title={titleForMeasure}
/>
);
})}
Expand Down