Skip to content

⚡️ Speed up function getActionChildrenPeekData by 21%#49

Open
codeflash-ai[bot] wants to merge 1 commit intoreleasefrom
codeflash/optimize-getActionChildrenPeekData-ml2839ta
Open

⚡️ Speed up function getActionChildrenPeekData by 21%#49
codeflash-ai[bot] wants to merge 1 commit intoreleasefrom
codeflash/optimize-getActionChildrenPeekData-ml2839ta

Conversation

@codeflash-ai
Copy link

@codeflash-ai codeflash-ai bot commented Jan 31, 2026

📄 21% (0.21x) speedup for getActionChildrenPeekData in app/client/src/utils/FilterInternalProperties/Action.ts

⏱️ Runtime : 256 microseconds 212 microseconds (best of 250 runs)

📝 Explanation and details

The optimized code achieves a 21% runtime improvement (256μs → 212μs) through three targeted optimizations that reduce overhead in the hot iteration path:

Key Performance Improvements:

  1. Iterator Optimization: Replaced Object.keys(definitions).forEach() with a cached-length for loop (for (let i = 0, len = keys.length; i < len; i++)). This eliminates the forEach callback closure allocation on every iteration, which the line profiler confirms was expensive (17.4% of time spent on the forEach line in the original).

  2. Function Object Reuse: Created a single EMPTY_FN constant instead of allocating a new empty function object each time "run" or "clear" is encountered. In TypeScript/JavaScript, function expressions create new objects, so this prevents redundant allocations when processing multiple actions or definitions with these keys.

  3. Early Exit + Switch Statement: Changed from nested if-else chains to an early continue for keys containing "!" followed by a switch statement for the special cases. The line profiler shows the original compound conditional check (if (key === "data" || key === "isLoading" || key === "responseMeta")) consumed 78.2% of execution time. The switch statement provides better branch prediction and reduces the number of equality comparisons needed per iteration.

Test Performance Patterns:

  • Small/medium definitions (~10 keys): 8-52% faster in individual tests (e.g., "should handle action with isLoading as false" shows 52.8% improvement)
  • Large definitions (500 keys): 16.6% faster, with the optimization showing its value when iterating over many keys
  • Edge cases with minimal work: Similar performance to baseline (as expected when the hot path isn't exercised)

The optimization is particularly effective for actions with typical definition sizes (5-20 keys), which appear to be the common case based on the test patterns. The changes maintain identical behavior while reducing per-key iteration overhead through better memory efficiency and branch prediction.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 529 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Click to see Generated Regression Tests
// @ts-nocheck
// imports and mocks
jest.mock('ee/utils/autocomplete/EntityDefinitions', () => {
    // Provide a mock entityDefinitions with a mockable ACTION function
    return {
        entityDefinitions: {
            ACTION: jest.fn(),
        },
    };
});

import { entityDefinitions } from 'ee/utils/autocomplete/EntityDefinitions';
import { getActionChildrenPeekData } from '../src/utils/FilterInternalProperties/Action';

// unit tests
describe('getActionChildrenPeekData', () => {
    afterEach(() => {
        // reset the mock between tests to avoid cross-test pollution
        entityDefinitions.ACTION.mockReset();
    });

    // Basic Test Cases
    describe('Basic functionality', () => {
        test('should handle normal input', () => {
            // This test covers the typical happy-path:
            // - definitions contain a mixture of public keys, special keys (data/isLoading/responseMeta/run/clear),
            //   and internal keys (containing "!").
            // - The function should include only allowed keys in peekData:
            //   - copy values for data/isLoading/responseMeta from the action object
            //   - provide placeholder functions for run and clear
            //   - ignore keys containing "!" and other non-special keys

            const actionName = 'myAction';
            const dataTreeAction = {
                data: { items: [1, 2, 3] },
                isLoading: false,
                responseMeta: { status: 200 },
                // original methods (should NOT be returned verbatim)
                run: () => 'originalRun',
                clear: () => 'originalClear',
                otherProp: 'shouldBeIgnored',
                '!internalProp': 'secret', // even if present on action, definitions with "!" should prevent exposure
            };

            // Mock definitions returned by entityDefinitions.ACTION
            const definitions = {
                data: {},
                isLoading: {},
                responseMeta: {},
                run: {},
                clear: {},
                otherProp: {},
                '!internalProp': {},
            };

            entityDefinitions.ACTION.mockImplementation(() => definitions);

            const dataTree = { [actionName]: dataTreeAction };

            const result = getActionChildrenPeekData(actionName, dataTree);

            // Expect result to be an object with a peekData property
            expect(result).toBeTruthy();  // 7.81μs -> 9.39μs (16.8% slower)
            expect(typeof result).toBe('object');
            expect(result).toHaveProperty('peekData');

            const { peekData } = result;

            // Check that the three data keys are present and refer to the actual values on the action
            expect(peekData.data).toBe(dataTreeAction.data);
            expect(peekData.isLoading).toBe(dataTreeAction.isLoading);
            expect(peekData.responseMeta).toBe(dataTreeAction.responseMeta);

            // run and clear should be functions provided by getActionChildrenPeekData (not the original methods)
            expect(typeof peekData.run).toBe('function');
            expect(typeof peekData.clear).toBe('function');
            expect(peekData.run).not.toBe(dataTreeAction.run);
            expect(peekData.clear).not.toBe(dataTreeAction.clear);

            // otherProp should NOT be present in the peekData
            expect(peekData).not.toHaveProperty('otherProp');

            // internal keys (containing "!") should not be included
            expect(peekData).not.toHaveProperty('!internalProp');
        });
    });

    // Edge Test Cases
    describe('Edge cases', () => {
        test('should return undefined when the action does not exist in the dataTree', () => {
            // If there's no action matching actionName in dataTree, function should return undefined.
            const actionName = 'missingAction';
            // Ensure definitions would not even be called in this case, but we still provide a mock
            entityDefinitions.ACTION.mockImplementation(() => {
                throw new Error('Should not be called');
            });

            const dataTree = {
                someOtherAction: {},
            };

            const result = getActionChildrenPeekData(actionName, dataTree);

            expect(result).toBeUndefined();  // 649ns -> 673ns (3.57% slower)
        });

        test('should produce empty peekData when definitions contain only internal keys (with "!")', () => {
            // When definitions only contain keys with "!", none should be exposed in peekData
            const actionName = 'actionWithOnlyInternalDefs';
            const dataTreeAction = {
                data: { foo: 'bar' }, // even if action has data, definition excludes it
            };

            const definitions = {
                '!internal1': {},
                'also!internal': {},
            };

            entityDefinitions.ACTION.mockImplementation(() => definitions);

            const dataTree = { [actionName]: dataTreeAction };

            const result = getActionChildrenPeekData(actionName, dataTree);

            expect(result).toBeTruthy();
            expect(result).toHaveProperty('peekData');
            expect(Object.keys(result.peekData).length).toBe(0);
        });

        test('should include keys with undefined values if action lacks them but definitions list them', () => {
            // If definitions list data/isLoading/responseMeta but the action object doesn't have those properties,
            // the peekData should contain those keys with undefined values (preserving the "shape").
            const actionName = 'actionWithMissingProps';
            const dataTreeAction = {
                // intentionally does not define data/isLoading/responseMeta
            };

            const definitions = {
                data: {},
                isLoading: {},
                responseMeta: {},
            };

            entityDefinitions.ACTION.mockImplementation(() => definitions);

            const dataTree = { [actionName]: dataTreeAction };

            const result = getActionChildrenPeekData(actionName, dataTree);

            expect(result).toBeTruthy();  // 2.19μs -> 2.08μs (5.09% faster)
            expect(result).toHaveProperty('peekData');

            const { peekData } = result;

            expect(Object.prototype.hasOwnProperty.call(peekData, 'data')).toBe(true);
            expect(peekData.data).toBeUndefined();

            expect(Object.prototype.hasOwnProperty.call(peekData, 'isLoading')).toBe(true);
            expect(peekData.isLoading).toBeUndefined();

            expect(Object.prototype.hasOwnProperty.call(peekData, 'responseMeta')).toBe(true);
            expect(peekData.responseMeta).toBeUndefined();
        });

        test('should ignore definition keys that include "!" anywhere in the key name', () => {
            // Keys that contain "!" anywhere should be filtered out even if they match special names when combined
            const actionName = 'actionWithExclamations';
            const dataTreeAction = {
                'da!ta': { bad: true },
                'is!Loading': true,
                'response!Meta': {},
                run: () => {},
                clear: () => {},
            };

            const definitions = {
                'da!ta': {},
                'is!Loading': {},
                'response!Meta': {},
                run: {},
                clear: {},
            };

            entityDefinitions.ACTION.mockImplementation(() => definitions);

            const dataTree = { [actionName]: dataTreeAction };

            const result = getActionChildrenPeekData(actionName, dataTree);

            expect(result).toBeTruthy();
            const { peekData } = result;

            // The keys with "!" should be excluded
            expect(peekData).not.toHaveProperty('da!ta');
            expect(peekData).not.toHaveProperty('is!Loading');
            expect(peekData).not.toHaveProperty('response!Meta');

            // run and clear should still appear
            expect(typeof peekData.run).toBe('function');
            expect(typeof peekData.clear).toBe('function');
        });
    });

    // Large Scale Test Cases
    describe('Performance tests', () => {
        test('should handle large inputs efficiently', () => {
            // This test generates a relatively large definitions object (but under 1000 elements as requested)
            // and ensures the function completes quickly and returns the expected minimal peekData.
            const actionName = 'largeAction';
            const dataTreeAction = {
                data: { big: 'payload' },
                isLoading: true,
                responseMeta: { ok: true },
                run: () => 'orig',
                clear: () => 'origClear',
            };

            // Build many keys (e.g., 500) with a mix of exclamation and normal keys.
            const definitions = {};
            const totalKeys = 500;
            for (let i = 0; i < totalKeys; i++) {
                // Every 7th key include an "!" to ensure many are filtered out
                const key = i % 7 === 0 ? `prop${i}!` : `prop${i}`;
                definitions[key] = {};
            }

            // Ensure special keys are also present among many keys
            definitions.data = {};
            definitions.isLoading = {};
            definitions.responseMeta = {};
            definitions.run = {};
            definitions.clear = {};

            entityDefinitions.ACTION.mockImplementation(() => definitions);

            const dataTree = { [actionName]: dataTreeAction };

            // Measure execution time to catch pathological slowdowns.
            const start = Date.now();
            const result = getActionChildrenPeekData(actionName, dataTree);
            const durationMs = Date.now() - start;

            expect(result).toBeDefined();  // 94.1μs -> 80.7μs (16.6% faster)
            expect(result).toHaveProperty('peekData');

            const { peekData } = result;

            // Despite many definition keys, only the special public keys should be present
            expect(peekData.data).toBe(dataTreeAction.data);
            expect(peekData.isLoading).toBe(dataTreeAction.isLoading);
            expect(peekData.responseMeta).toBe(dataTreeAction.responseMeta);
            expect(typeof peekData.run).toBe('function');
            expect(typeof peekData.clear).toBe('function');

            // No other propX keys should be included
            expect(Object.keys(peekData).length).toBe(5);

            // Ensure it completed in a reasonable time (arbitrary threshold; should be tiny for this size)
            // Using 200ms as a conservative upper limit for such a small loop in JS.
            expect(durationMs).toBeLessThan(200);
        });
    });
});
// @ts-nocheck
// imports
import { getActionChildrenPeekData } from '../src/utils/FilterInternalProperties/Action';

// Mock the external dependencies
jest.mock('ee/utils/autocomplete/EntityDefinitions', () => ({
  entityDefinitions: {
    ACTION: jest.fn((actionEntity, options) => {
      // Return a mock definitions object with both internal and public properties
      return {
        'data': true,
        'isLoading': true,
        'responseMeta': true,
        'run': true,
        'clear': true,
        '!internal_prop': true,
        'error': true,
        '!debug_info': true,
      };
    }),
  },
}));

// unit tests
describe('getActionChildrenPeekData', () => {
  // Basic Test Cases
  describe('Basic functionality', () => {
    test('should return peekData object with correct structure when action exists', () => {
      // Arrange
      const actionName = 'testAction';
      const mockDataTree = {
        testAction: {
          data: { result: 'success' },
          isLoading: false,
          responseMeta: { status: 200 },
          run: () => {},
          clear: () => {},
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result).toBeDefined();  // 15.4μs -> 14.3μs (8.14% faster)
      expect(result).toHaveProperty('peekData');
      expect(typeof result.peekData).toBe('object');
    });

    test('should include data property in peekData when action has data', () => {
      // Arrange
      const actionName = 'myAction';
      const testData = { userId: 123, userName: 'John' };
      const mockDataTree = {
        myAction: {
          data: testData,
          isLoading: false,
          responseMeta: {},
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result.peekData).toHaveProperty('data');  // 9.36μs -> 6.82μs (37.3% faster)
      expect(result.peekData.data).toEqual(testData);
    });

    test('should include isLoading property in peekData', () => {
      // Arrange
      const actionName = 'loadAction';
      const mockDataTree = {
        loadAction: {
          isLoading: true,
          data: null,
          responseMeta: {},
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result.peekData).toHaveProperty('isLoading');  // 6.52μs -> 5.84μs (11.6% faster)
      expect(result.peekData.isLoading).toBe(true);
    });

    test('should include responseMeta property in peekData', () => {
      // Arrange
      const actionName = 'apiAction';
      const mockMeta = { statusCode: 200, headers: { 'content-type': 'application/json' } };
      const mockDataTree = {
        apiAction: {
          responseMeta: mockMeta,
          isLoading: false,
          data: {},
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result.peekData).toHaveProperty('responseMeta');  // 5.48μs -> 4.85μs (13.0% faster)
      expect(result.peekData.responseMeta).toEqual(mockMeta);
    });

    test('should include run function in peekData', () => {
      // Arrange
      const actionName = 'execAction';
      const mockDataTree = {
        execAction: {
          run: () => {},
          data: {},
          isLoading: false,
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result.peekData).toHaveProperty('run');  // 5.87μs -> 5.13μs (14.5% faster)
      expect(typeof result.peekData.run).toBe('function');
    });

    test('should include clear function in peekData', () => {
      // Arrange
      const actionName = 'clearAction';
      const mockDataTree = {
        clearAction: {
          clear: () => {},
          data: {},
          isLoading: false,
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result.peekData).toHaveProperty('clear');  // 6.58μs -> 5.13μs (28.4% faster)
      expect(typeof result.peekData.clear).toBe('function');
    });

    test('should exclude properties with exclamation mark in key', () => {
      // Arrange
      const actionName = 'filteredAction';
      const mockDataTree = {
        filteredAction: {
          data: { value: 1 },
          isLoading: false,
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      // Properties with "!" should not be included
      expect(Object.keys(result.peekData)).not.toEqual(  // 6.34μs -> 4.97μs (27.5% faster)
        expect.arrayContaining([
          expect.stringMatching(/!/),
        ])
      );
    });
  });

  // Edge Test Cases
  describe('Edge cases', () => {
    test('should return undefined when action does not exist in dataTree', () => {
      // Arrange
      const actionName = 'nonExistentAction';
      const mockDataTree = {
        otherAction: { data: {} },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result).toBeUndefined();  // 1.20μs -> 1.18μs (2.12% faster)
    });

    test('should handle action with null data property', () => {
      // Arrange
      const actionName = 'nullDataAction';
      const mockDataTree = {
        nullDataAction: {
          data: null,
          isLoading: false,
          responseMeta: null,
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result.peekData).toHaveProperty('data');  // 6.39μs -> 5.64μs (13.3% faster)
      expect(result.peekData.data).toBeNull();
    });

    test('should handle action with undefined data property', () => {
      // Arrange
      const actionName = 'undefinedDataAction';
      const mockDataTree = {
        undefinedDataAction: {
          data: undefined,
          isLoading: false,
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result.peekData).toHaveProperty('data');  // 5.68μs -> 6.14μs (7.50% slower)
      expect(result.peekData.data).toBeUndefined();
    });

    test('should handle action with empty object data', () => {
      // Arrange
      const actionName = 'emptyAction';
      const mockDataTree = {
        emptyAction: {
          data: {},
          isLoading: false,
          responseMeta: {},
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result.peekData.data).toEqual({});  // 5.31μs -> 5.61μs (5.21% slower)
    });

    test('should handle action with empty array data', () => {
      // Arrange
      const actionName = 'arrayAction';
      const mockDataTree = {
        arrayAction: {
          data: [],
          isLoading: false,
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result.peekData.data).toEqual([]);  // 5.74μs -> 6.98μs (17.8% slower)
    });

    test('should handle action with isLoading as false', () => {
      // Arrange
      const actionName = 'notLoadingAction';
      const mockDataTree = {
        notLoadingAction: {
          isLoading: false,
          data: { status: 'complete' },
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result.peekData.isLoading).toBe(false);  // 5.75μs -> 3.76μs (52.8% faster)
    });

    test('should handle action name with special characters', () => {
      // Arrange
      const actionName = 'test_Action-123';
      const mockDataTree = {
        'test_Action-123': {
          data: { value: 'special' },
          isLoading: false,
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result).toBeDefined();  // 5.51μs -> 4.06μs (35.7% faster)
      expect(result.peekData.data).toEqual({ value: 'special' });
    });

    test('should handle empty action name', () => {
      // Arrange
      const actionName = '';
      const mockDataTree = {
        '': {
          data: { value: 'empty name' },
          isLoading: false,
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result).toBeDefined();  // 5.53μs -> 4.11μs (34.5% faster)
      expect(result.peekData.data).toEqual({ value: 'empty name' });
    });

    test('should handle action with complex nested data structures', () => {
      // Arrange
      const actionName = 'complexAction';
      const complexData = {
        users: [
          { id: 1, roles: ['admin', 'user'] },
          { id: 2, roles: ['user'] },
        ],
        metadata: {
          timestamp: '2024-01-01',
          tags: { env: 'prod', version: '1.0' },
        },
      };
      const mockDataTree = {
        complexAction: {
          data: complexData,
          isLoading: false,
          responseMeta: { nested: { deep: { value: 'deep' } } },
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result.peekData.data).toEqual(complexData);  // 5.56μs -> 3.96μs (40.4% faster)
      expect(result.peekData.responseMeta.nested.deep.value).toBe('deep');
    });

    test('should not include properties that are not explicitly handled', () => {
      // Arrange
      const actionName = 'filterAction';
      const mockDataTree = {
        filterAction: {
          data: {},
          isLoading: false,
          responseMeta: {},
          customProp: 'should not appear',
          anotherCustom: 123,
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      // Only data, isLoading, responseMeta, run, and clear should be in peekData
      expect(result.peekData).not.toHaveProperty('customProp');  // 5.91μs -> 3.88μs (52.5% faster)
      expect(result.peekData).not.toHaveProperty('anotherCustom');
    });

    test('should create empty function objects for run and clear', () => {
      // Arrange
      const actionName = 'funcAction';
      const mockDataTree = {
        funcAction: {
          run: () => console.log('run'),
          clear: () => console.log('clear'),
          data: {},
          isLoading: false,
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      // The peekData functions should be callable (empty functions)
      expect(() => result.peekData.run()).not.toThrow();  // 7.02μs -> 2.92μs (141% faster)
      expect(() => result.peekData.clear()).not.toThrow();
    });
  });

  // Large Scale Test Cases
  describe('Performance tests', () => {
    test('should efficiently handle action with large data object', () => {
      // Arrange - Create a large data object with 500 properties
      const largeData = {};
      for (let i = 0; i < 500; i++) {
        largeData[`property_${i}`] = `value_${i}`;
      }

      const actionName = 'largeAction';
      const mockDataTree = {
        largeAction: {
          data: largeData,
          isLoading: false,
          responseMeta: {},
        },
      };

      // Act
      const startTime = Date.now();
      const result = getActionChildrenPeekData(actionName, mockDataTree);
      const endTime = Date.now();

      // Assert
      expect(result.peekData.data).toEqual(largeData);  // 6.16μs -> 2.50μs (146% faster)
      expect(endTime - startTime).toBeLessThan(100); // Should complete in less than 100ms
    });

    test('should handle action with deeply nested data structure', () => {
      // Arrange - Create deeply nested object
      let deepData = { value: 'deepest' };
      for (let i = 0; i < 50; i++) {
        deepData = { nested: deepData };
      }

      const actionName = 'deepAction';
      const mockDataTree = {
        deepAction: {
          data: deepData,
          isLoading: false,
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result.peekData.data).toEqual(deepData);  // 5.75μs -> 4.91μs (17.0% faster)
    });

    test('should handle dataTree with many actions', () => {
      // Arrange - Create dataTree with 100 actions
      const mockDataTree = {};
      for (let i = 0; i < 100; i++) {
        mockDataTree[`action_${i}`] = {
          data: { index: i },
          isLoading: false,
          responseMeta: {},
        };
      }

      // Act
      const startTime = Date.now();
      const result = getActionChildrenPeekData('action_50', mockDataTree);
      const endTime = Date.now();

      // Assert
      expect(result).toBeDefined();  // 6.33μs -> 2.37μs (167% faster)
      expect(result.peekData.data).toEqual({ index: 50 });
      expect(endTime - startTime).toBeLessThan(50); // Should be fast regardless of dataTree size
    });

    test('should handle action with large array data', () => {
      // Arrange - Create action with large array (500 items)
      const largeArray = Array.from({ length: 500 }, (_, i) => ({
        id: i,
        name: `item_${i}`,
        value: Math.random(),
      }));

      const actionName = 'arrayLargeAction';
      const mockDataTree = {
        arrayLargeAction: {
          data: largeArray,
          isLoading: false,
        },
      };

      // Act
      const startTime = Date.now();
      const result = getActionChildrenPeekData(actionName, mockDataTree);
      const endTime = Date.now();

      // Assert
      expect(result.peekData.data).toHaveLength(500);  // 6.82μs -> 4.70μs (45.0% faster)
      expect(result.peekData.data[0]).toEqual(largeArray[0]);
      expect(endTime - startTime).toBeLessThan(100);
    });

    test('should handle definitions with many properties', () => {
      // Arrange - Mock a definitions object with many properties
      const actionName = 'manyPropsAction';
      const mockDataTree = {
        manyPropsAction: {
          data: { result: 'ok' },
          isLoading: false,
          responseMeta: {},
          run: () => {},
          clear: () => {},
        },
      };

      // Act
      const result = getActionChildrenPeekData(actionName, mockDataTree);

      // Assert
      expect(result).toBeDefined();  // 6.15μs -> 4.89μs (25.8% faster)
      expect(Object.keys(result.peekData).length).toBeGreaterThan(0);
    });

    test('should handle repeated calls with same action efficiently', () => {
      // Arrange
      const actionName = 'cachedAction';
      const mockDataTree = {
        cachedAction: {
          data: { value: 'test' },
          isLoading: false,
        },
      };

      // Act - Call function multiple times
      const startTime = Date.now();
      for (let i = 0; i < 500; i++) {
        getActionChildrenPeekData(actionName, mockDataTree);
      }
      const endTime = Date.now();

      // Assert - Should handle repeated calls efficiently
      expect(endTime - startTime).toBeLessThan(500); // Should complete 500 iterations quickly
    });
  });
});

📊 Performance Profile

View detailed line-by-line performance analysis
To edit these changes git checkout codeflash/optimize-getActionChildrenPeekData-ml2839ta and push.

Codeflash

The optimized code achieves a **21% runtime improvement** (256μs → 212μs) through three targeted optimizations that reduce overhead in the hot iteration path:

**Key Performance Improvements:**

1. **Iterator Optimization**: Replaced `Object.keys(definitions).forEach()` with a cached-length `for` loop (`for (let i = 0, len = keys.length; i < len; i++)`). This eliminates the forEach callback closure allocation on every iteration, which the line profiler confirms was expensive (17.4% of time spent on the forEach line in the original).

2. **Function Object Reuse**: Created a single `EMPTY_FN` constant instead of allocating a new empty function object each time "run" or "clear" is encountered. In TypeScript/JavaScript, function expressions create new objects, so this prevents redundant allocations when processing multiple actions or definitions with these keys.

3. **Early Exit + Switch Statement**: Changed from nested if-else chains to an early `continue` for keys containing "!" followed by a `switch` statement for the special cases. The line profiler shows the original compound conditional check (`if (key === "data" || key === "isLoading" || key === "responseMeta")`) consumed 78.2% of execution time. The switch statement provides better branch prediction and reduces the number of equality comparisons needed per iteration.

**Test Performance Patterns:**
- **Small/medium definitions** (~10 keys): 8-52% faster in individual tests (e.g., "should handle action with isLoading as false" shows 52.8% improvement)
- **Large definitions** (500 keys): 16.6% faster, with the optimization showing its value when iterating over many keys
- **Edge cases with minimal work**: Similar performance to baseline (as expected when the hot path isn't exercised)

The optimization is particularly effective for actions with typical definition sizes (5-20 keys), which appear to be the common case based on the test patterns. The changes maintain identical behavior while reducing per-key iteration overhead through better memory efficiency and branch prediction.
@codeflash-ai codeflash-ai bot requested a review from misrasaurabh1 January 31, 2026 11:22
@codeflash-ai codeflash-ai bot added the ⚡️ codeflash Optimization PR opened by Codeflash AI label Jan 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

⚡️ codeflash Optimization PR opened by Codeflash AI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants