[ResponseOps] optimize building ecsFieldMap (#159251)

resolves https://github.com/elastic/kibana/issues/157772

Previously on my M1 Macbook, the `ecsFieldMap` constant takes about 170
ms to be created. It appears this is another case of `array::reduce()`
and object spread causing performance issues.

Converting to (essentially) a filter and map got the time down to 4 ms.

Slightly critical even though this is only ever run once - because it's
run at startup time, and blocking everything else from running.

See:

-
https://www.richsnapp.com/article/2019/06-09-reduce-spread-anti-pattern
-
https://prateeksurana.me/blog/why-using-object-spread-with-reduce-bad-idea/
This commit is contained in:
Patrick Mueller 2023-06-08 10:06:01 -04:00 committed by GitHub
parent 1ca29efb87
commit 6e81ae83bc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -11,25 +11,23 @@ import { EcsMetadata, FieldMap } from './types';
const EXCLUDED_TYPES = ['constant_keyword'];
export const ecsFieldMap: FieldMap = Object.keys(EcsFlat).reduce((acc, currKey) => {
const value: EcsMetadata = EcsFlat[currKey as keyof typeof EcsFlat];
// Exclude excluded types
if (EXCLUDED_TYPES.includes(value.type)) {
return acc;
}
return {
...acc,
[currKey]: {
type: value.type,
array: value.normalize.includes('array'),
required: !!value.required,
...(value.scaling_factor ? { scaling_factor: value.scaling_factor } : {}),
...(value.ignore_above ? { ignore_above: value.ignore_above } : {}),
...(value.multi_fields ? { multi_fields: value.multi_fields } : {}),
},
};
}, {});
export const ecsFieldMap: FieldMap = Object.fromEntries(
Object.entries(EcsFlat)
.filter(([_, value]) => !EXCLUDED_TYPES.includes(value.type))
.map(([key, _]) => {
const value: EcsMetadata = EcsFlat[key as keyof typeof EcsFlat];
return [
key,
{
type: value.type,
array: value.normalize.includes('array'),
required: !!value.required,
...(value.scaling_factor ? { scaling_factor: value.scaling_factor } : {}),
...(value.ignore_above ? { ignore_above: value.ignore_above } : {}),
...(value.multi_fields ? { multi_fields: value.multi_fields } : {}),
},
];
})
);
export type EcsFieldMap = typeof ecsFieldMap;