Skip to content

⚡️ Speed up function getNearestAbove by 45%#20

Open
codeflash-ai[bot] wants to merge 1 commit intoreleasefrom
codeflash/optimize-getNearestAbove-ml1zpyxk
Open

⚡️ Speed up function getNearestAbove by 45%#20
codeflash-ai[bot] wants to merge 1 commit intoreleasefrom
codeflash/optimize-getNearestAbove-ml1zpyxk

Conversation

@codeflash-ai
Copy link

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

📄 45% (0.45x) speedup for getNearestAbove in app/client/src/utils/autoHeight/helpers.ts

⏱️ Runtime : 198 microseconds 137 microseconds (best of 10 runs)

📝 Explanation and details

The optimized code achieves a 44% runtime improvement (198μs → 137μs) through strategic caching of repositionedBoxes lookups. This is a classic example of eliminating redundant object property accesses in a hot loop.

What Changed:
The optimization caches two frequently-accessed values at the beginning of each reduce iteration:

const nextRepositioned = repositionedBoxes[next];
const prevRepositioned = repositionedBoxes[prev[0]];

Why This Improves Performance:

  1. Eliminates Redundant Lookups: In the original code, repositionedBoxes[next] and repositionedBoxes[prev[0]] are accessed multiple times within the same iteration—first for checking existence, then for property access (.bottomRow, .topRow). Each object property lookup has a small cost that compounds in a reduce operation.

  2. JavaScript Object Access Cost: Hash map lookups via bracket notation (repositionedBoxes[key]) are more expensive than variable reads. By performing the lookup once and storing the result, the optimization replaces 4-6 object accesses per iteration with 2 initial lookups plus fast variable reads.

  3. Cascading Effect in Reduce: Since this runs in a reduce() over all aboves boxes, the savings multiply. Test results show dramatic improvements in large-scale scenarios:

    • 500 items: 88.5μs → 50.9μs (74% faster)
    • 300 items with ties: 32.0μs → 14.2μs (126% faster)
    • 100 items: 10.8μs → 11.2μs (modest 4% slower, likely noise)

Best Performance Gains:
The optimization excels when:

  • Many boxes exist with repositioning data (50+ boxes: 23.5% faster)
  • Multiple boxes share the same bottomRow requiring equality checks (300 items: 126% faster)
  • Cascading comparisons occur where the same keys are checked repeatedly

Impact on Workloads:
Without function_references, we can't determine call frequency, but given this is in autoHeight/helpers.ts and handles box positioning logic, it likely runs during layout calculations—potentially multiple times per user interaction in UI frameworks. The 44% improvement could translate to smoother rendering in canvas/grid-based applications where many widgets need position recalculation.

The optimization is purely mechanical (caching repeated lookups) with no algorithmic changes, making it safe and predictable across all test scenarios.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 28 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Click to see Generated Regression Tests
// @ts-nocheck
// imports
import { getNearestAbove } from '../src/utils/autoHeight/helpers';

// unit tests
describe('getNearestAbove', () => {
    // Basic Test Cases
    describe('Basic functionality', () => {
        test('should handle normal input: pick the above with the largest bottomRow', () => {
            // Simple tree: three aboves with distinct bottomRow values.
            const tree = {
                target: {
                    aboves: ['a', 'b', 'c'],
                    belows: [],
                    topRow: 0,
                    bottomRow: 0,
                    originalTopRow: 0,
                    originalBottomRow: 0,
                    distanceToNearestAbove: 0,
                },
                a: {
                    aboves: [],
                    belows: [],
                    topRow: 0,
                    bottomRow: 10,
                    originalTopRow: 0,
                    originalBottomRow: 10,
                    distanceToNearestAbove: 0,
                },
                b: {
                    aboves: [],
                    belows: [],
                    topRow: 0,
                    bottomRow: 20,
                    originalTopRow: 0,
                    originalBottomRow: 20,
                    distanceToNearestAbove: 0,
                },
                c: {
                    aboves: [],
                    belows: [],
                    topRow: 0,
                    bottomRow: 15,
                    originalTopRow: 0,
                    originalBottomRow: 15,
                    distanceToNearestAbove: 0,
                },
            };

            const repositionedBoxes = {}; // no repositioning
            const result = getNearestAbove(tree, 'target', repositionedBoxes);

            // Expect the box with bottomRow 20 ('b') to be selected.
            expect(Array.isArray(result)).toBe(true);  // 1.89μs -> 2.06μs (8.58% slower)
            expect(result).toEqual(['b']);
        });

        test('should return single element when there is only one above', () => {
            const tree = {
                target: {
                    aboves: ['solo'],
                    belows: [],
                    topRow: 0,
                    bottomRow: 0,
                    originalTopRow: 0,
                    originalBottomRow: 0,
                    distanceToNearestAbove: 0,
                },
                solo: {
                    aboves: [],
                    belows: [],
                    topRow: 5,
                    bottomRow: 15,
                    originalTopRow: 5,
                    originalBottomRow: 15,
                    distanceToNearestAbove: 0,
                },
            };

            const result = getNearestAbove(tree, 'target', {});
            expect(result).toEqual(['solo']);  // 1.09μs -> 800ns (36.2% faster)
        });
    });

    // Edge Test Cases
    describe('Edge cases', () => {
        test('should return empty array when there are no aboves', () => {
            // If the target has no aboves, the reduce should return the initial [].
            const tree = {
                target: {
                    aboves: [],
                    belows: [],
                    topRow: 0,
                    bottomRow: 0,
                    originalTopRow: 0,
                    originalBottomRow: 0,
                    distanceToNearestAbove: 0,
                },
            };

            const result = getNearestAbove(tree, 'target', {});
            expect(Array.isArray(result)).toBe(true);  // 656ns -> 620ns (5.81% faster)
            expect(result).toEqual([]);
        });

        test('should respect repositionedBoxes override when determining bottomRow', () => {
            // 'a' originally has higher bottomRow than 'b', but repositionedBoxes
            // updates 'b' to have the highest bottomRow -> 'b' should be chosen.
            const tree = {
                target: { aboves: ['a', 'b'], belows: [], topRow: 0, bottomRow: 0, originalTopRow: 0, originalBottomRow: 0, distanceToNearestAbove: 0 },
                a: { aboves: [], belows: [], topRow: 0, bottomRow: 30, originalTopRow: 0, originalBottomRow: 30, distanceToNearestAbove: 0 },
                b: { aboves: [], belows: [], topRow: 0, bottomRow: 10, originalTopRow: 0, originalBottomRow: 10, distanceToNearestAbove: 0 },
            };

            const repositionedBoxes = {
                b: { topRow: 0, bottomRow: 40 }, // now b has highest bottomRow
            };

            const result = getNearestAbove(tree, 'target', repositionedBoxes);
            expect(result).toEqual(['b']);  // 975ns -> 899ns (8.45% faster)
        });

        test('should return multiple ids when aboves share the same bottomRow (no repositioned edge cases)', () => {
            // When two or more aboves have identical bottomRow and no repositionedBoxes
            // special cases apply, function should return all equal bottom-most aboves.
            const tree = {
                target: { aboves: ['a', 'b', 'c'], belows: [], topRow: 0, bottomRow: 0, originalTopRow: 0, originalBottomRow: 0, distanceToNearestAbove: 0 },
                a: { aboves: [], belows: [], topRow: 0, bottomRow: 10, originalTopRow: 0, originalBottomRow: 10, distanceToNearestAbove: 0 },
                b: { aboves: [], belows: [], topRow: 0, bottomRow: 10, originalTopRow: 0, originalBottomRow: 10, distanceToNearestAbove: 0 },
                c: { aboves: [], belows: [], topRow: 0, bottomRow: 10, originalTopRow: 0, originalBottomRow: 10, distanceToNearestAbove: 0 },
            };

            const result = getNearestAbove(tree, 'target', {});
            // Expect all three in the order they appeared because none of the special
            // repositioned collapse conditions apply.
            expect(result).toEqual(['a', 'b', 'c']);  // 1.43μs -> 1.22μs (16.9% faster)
        });

        test('when prev is collapsed in repositionedBoxes (bottomRow === topRow), keep prev only', () => {
            // Two aboves with equal original bottomRows.
            // If prev (the first one) is collapsed in reposition (bottom === top),
            // function should return prev unchanged (i.e., do not add the next).
            const tree = {
                target: { aboves: ['a', 'b'], belows: [], topRow: 0, bottomRow: 0, originalTopRow: 0, originalBottomRow: 0, distanceToNearestAbove: 0 },
                a: { aboves: [], belows: [], topRow: 5, bottomRow: 10, originalTopRow: 5, originalBottomRow: 10, distanceToNearestAbove: 0 },
                b: { aboves: [], belows: [], topRow: 6, bottomRow: 10, originalTopRow: 6, originalBottomRow: 10, distanceToNearestAbove: 0 },
            };

            const repositionedBoxes = {
                a: { topRow: 10, bottomRow: 10 }, // collapsed to zero height (top == bottom)
            };

            const result = getNearestAbove(tree, 'target', repositionedBoxes);
            // Because prev (a) is collapsed, equal-bottom next (b) should not be included.
            expect(result).toEqual(['a']);  // 1.05μs -> 842ns (24.3% faster)
        });

        test('when next is collapsed in repositionedBoxes (bottomRow === topRow), prefer next alone', () => {
            // Two aboves with equal original bottomRows.
            // If the next one is collapsed in repositioning, function should prefer [next].
            const tree = {
                target: { aboves: ['a', 'b'], belows: [], topRow: 0, bottomRow: 0, originalTopRow: 0, originalBottomRow: 0, distanceToNearestAbove: 0 },
                a: { aboves: [], belows: [], topRow: 5, bottomRow: 10, originalTopRow: 5, originalBottomRow: 10, distanceToNearestAbove: 0 },
                b: { aboves: [], belows: [], topRow: 6, bottomRow: 10, originalTopRow: 6, originalBottomRow: 10, distanceToNearestAbove: 0 },
            };

            const repositionedBoxes = {
                b: { topRow: 10, bottomRow: 10 }, // collapsed
            };

            const result = getNearestAbove(tree, 'target', repositionedBoxes);
            // Because next (b) is collapsed, function returns [b] per implementation.
            expect(result).toEqual(['b']);  // 1.05μs -> 992ns (5.54% faster)
        });

        test('repositionedBoxes should be respected for both prev[0] and next during comparisons', () => {
            // Confirm that when prev was initially chosen but later repositioned to a smaller bottomRow,
            // a subsequent 'next' with a higher bottomRow (or repositioned bottomRow) replaces prev.
            const tree = {
                target: { aboves: ['a', 'b', 'c'], belows: [], topRow: 0, bottomRow: 0, originalTopRow: 0, originalBottomRow: 0, distanceToNearestAbove: 0 },
                a: { aboves: [], belows: [], topRow: 0, bottomRow: 30, originalTopRow: 0, originalBottomRow: 30, distanceToNearestAbove: 0 },
                b: { aboves: [], belows: [], topRow: 0, bottomRow: 10, originalTopRow: 0, originalBottomRow: 10, distanceToNearestAbove: 0 },
                c: { aboves: [], belows: [], topRow: 0, bottomRow: 25, originalTopRow: 0, originalBottomRow: 25, distanceToNearestAbove: 0 },
            };

            // 'a' initially has the largest bottomRow (30). But repositionedBoxes reduces 'a' to 5,
            // while 'c' gets repositioned to 40. Final winner should be 'c'.
            const repositionedBoxes = {
                a: { topRow: 5, bottomRow: 5 },
                c: { topRow: 24, bottomRow: 40 },
            };

            const result = getNearestAbove(tree, 'target', repositionedBoxes);
            expect(result).toEqual(['c']);  // 1.14μs -> 1.01μs (12.5% faster)
        });
    });

    // Large Scale Test Cases
    describe('Performance tests', () => {
        test('should handle a large number of aboves and return the highest bottomRow efficiently', () => {
            // Create a relatively large list of aboves (500 items) with strictly increasing bottomRows.
            // Ensure the function returns the id with the largest bottomRow.
            const COUNT = 500; // well under the 1000 element guidance
            const aboves = [];
            const tree = {
                target: { aboves: [], belows: [], topRow: 0, bottomRow: 0, originalTopRow: 0, originalBottomRow: 0, distanceToNearestAbove: 0 },
            };

            for (let i = 0; i < COUNT; i++) {
                const id = `n${i}`;
                aboves.push(id);
                tree[id] = {
                    aboves: [],
                    belows: [],
                    topRow: i, // arbitrary
                    bottomRow: i, // increasing bottomRow -> last one is largest
                    originalTopRow: i,
                    originalBottomRow: i,
                    distanceToNearestAbove: 0,
                };
            }

            tree.target.aboves = aboves;

            const result = getNearestAbove(tree, 'target', {});
            // The highest bottomRow is COUNT - 1, so expect that single id.
            expect(result).toEqual([`n${COUNT - 1}`]);  // 88.5μs -> 50.9μs (74.0% faster)
            // Also ensure the function returns quickly (this isn't a strict perf test,
            // but running within a reasonable time is expected in unit tests).
        });

        test('large input with many equal highest bottomRows should return all those ids', () => {
            // Create 300 items: first 290 have lower bottomRows, last 10 share the same highest bottomRow.
            const lowerCount = 290;
            const tieCount = 10;
            const tree = {
                target: { aboves: [], belows: [], topRow: 0, bottomRow: 0, originalTopRow: 0, originalBottomRow: 0, distanceToNearestAbove: 0 },
            };
            const aboves = [];

            for (let i = 0; i < lowerCount; i++) {
                const id = `low${i}`;
                aboves.push(id);
                tree[id] = {
                    aboves: [],
                    belows: [],
                    topRow: 0,
                    bottomRow: i,
                    originalTopRow: 0,
                    originalBottomRow: i,
                    distanceToNearestAbove: 0,
                };
            }

            // Add tieCount items all with the same highest bottomRow
            const highest = 1000;
            const expectedTieIds = [];
            for (let j = 0; j < tieCount; j++) {
                const id = `tie${j}`;
                expectedTieIds.push(id);
                aboves.push(id);
                tree[id] = {
                    aboves: [],
                    belows: [],
                    topRow: 0,
                    bottomRow: highest,
                    originalTopRow: 0,
                    originalBottomRow: highest,
                    distanceToNearestAbove: 0,
                };
            }

            tree.target.aboves = aboves;

            const result = getNearestAbove(tree, 'target', {});
            // All tied highest bottomRow items should be returned in the order encountered.
            expect(result).toEqual(expectedTieIds);  // 32.0μs -> 14.2μs (126% faster)
            // Sanity checks
            expect(result.length).toBe(tieCount);
            expect(result[0]).toBe('tie0');
        });
    });
});
// @ts-nocheck
import { getNearestAbove } from '../src/utils/autoHeight/helpers';

describe('getNearestAbove', () => {
  // ========== Basic Test Cases ==========
  describe('Basic functionality', () => {
    test('should return single nearest above box when only one above exists', () => {
      const tree = {
        box1: {
          aboves: ['box2'],
          belows: [],
          topRow: 10,
          bottomRow: 15,
          originalTopRow: 10,
          originalBottomRow: 15,
          distanceToNearestAbove: 5,
        },
        box2: {
          aboves: [],
          belows: ['box1'],
          topRow: 0,
          bottomRow: 8,
          originalTopRow: 0,
          originalBottomRow: 8,
          distanceToNearestAbove: 0,
        },
      };
      const repositionedBoxes = {};

      const result = getNearestAbove(tree, 'box1', repositionedBoxes);

      expect(result).toEqual(['box2']);  // 1.74μs -> 1.86μs (6.82% slower)
    });

    test('should return nearest box when multiple aboves exist with different bottomRows', () => {
      const tree = {
        box1: {
          aboves: ['box2', 'box3'],
          belows: [],
          topRow: 20,
          bottomRow: 25,
          originalTopRow: 20,
          originalBottomRow: 25,
          distanceToNearestAbove: 0,
        },
        box2: {
          aboves: [],
          belows: ['box1'],
          topRow: 0,
          bottomRow: 10,
          originalTopRow: 0,
          originalBottomRow: 10,
          distanceToNearestAbove: 0,
        },
        box3: {
          aboves: [],
          belows: ['box1'],
          topRow: 5,
          bottomRow: 18,
          originalTopRow: 5,
          originalBottomRow: 18,
          distanceToNearestAbove: 0,
        },
      };
      const repositionedBoxes = {};

      const result = getNearestAbove(tree, 'box1', repositionedBoxes);

      expect(result).toEqual(['box3']);  // 1.49μs -> 1.55μs (4.37% slower)
    });

    test('should return all boxes with same highest bottomRow when they are equal', () => {
      const tree = {
        box1: {
          aboves: ['box2', 'box3'],
          belows: [],
          topRow: 20,
          bottomRow: 25,
          originalTopRow: 20,
          originalBottomRow: 25,
          distanceToNearestAbove: 0,
        },
        box2: {
          aboves: [],
          belows: ['box1'],
          topRow: 0,
          bottomRow: 15,
          originalTopRow: 0,
          originalBottomRow: 15,
          distanceToNearestAbove: 0,
        },
        box3: {
          aboves: [],
          belows: ['box1'],
          topRow: 5,
          bottomRow: 15,
          originalTopRow: 5,
          originalBottomRow: 15,
          distanceToNearestAbove: 0,
        },
      };
      const repositionedBoxes = {};

      const result = getNearestAbove(tree, 'box1', repositionedBoxes);

      expect(result).toEqual(['box2', 'box3']);  // 1.93μs -> 1.23μs (57.3% faster)
    });

    test('should use repositioned bottomRow when box has been repositioned', () => {
      const tree = {
        box1: {
          aboves: ['box2', 'box3'],
          belows: [],
          topRow: 20,
          bottomRow: 25,
          originalTopRow: 20,
          originalBottomRow: 25,
          distanceToNearestAbove: 0,
        },
        box2: {
          aboves: [],
          belows: ['box1'],
          topRow: 0,
          bottomRow: 10,
          originalTopRow: 0,
          originalBottomRow: 10,
          distanceToNearestAbove: 0,
        },
        box3: {
          aboves: [],
          belows: ['box1'],
          topRow: 5,
          bottomRow: 12,
          originalTopRow: 5,
          originalBottomRow: 12,
          distanceToNearestAbove: 0,
        },
      };
      const repositionedBoxes = {
        box2: { topRow: 0, bottomRow: 18 },
      };

      const result = getNearestAbove(tree, 'box1', repositionedBoxes);

      expect(result).toEqual(['box2']);  // 923ns -> 827ns (11.6% faster)
    });

    test('should handle chain of above boxes correctly', () => {
      const tree = {
        box1: {
          aboves: ['box2', 'box3', 'box4'],
          belows: [],
          topRow: 30,
          bottomRow: 35,
          originalTopRow: 30,
          originalBottomRow: 35,
          distanceToNearestAbove: 0,
        },
        box2: {
          aboves: [],
          belows: ['box1'],
          topRow: 0,
          bottomRow: 5,
          originalTopRow: 0,
          originalBottomRow: 5,
          distanceToNearestAbove: 0,
        },
        box3: {
          aboves: [],
          belows: ['box1'],
          topRow: 10,
          bottomRow: 20,
          originalTopRow: 10,
          originalBottomRow: 20,
          distanceToNearestAbove: 0,
        },
        box4: {
          aboves: [],
          belows: ['box1'],
          topRow: 15,
          bottomRow: 25,
          originalTopRow: 15,
          originalBottomRow: 25,
          distanceToNearestAbove: 0,
        },
      };
      const repositionedBoxes = {};

      const result = getNearestAbove(tree, 'box1', repositionedBoxes);

      expect(result).toEqual(['box4']);  // 1.08μs -> 1.06μs (2.65% faster)
    });
  });

  // ========== Edge Test Cases ==========
  describe('Edge cases', () => {
    test('should return empty array when no aboves exist', () => {
      const tree = {
        box1: {
          aboves: [],
          belows: [],
          topRow: 10,
          bottomRow: 15,
          originalTopRow: 10,
          originalBottomRow: 15,
          distanceToNearestAbove: 0,
        },
      };
      const repositionedBoxes = {};

      const result = getNearestAbove(tree, 'box1', repositionedBoxes);

      expect(result).toEqual([]);  // 649ns -> 633ns (2.53% faster)
    });

    test('should handle repositioned box with topRow equal to bottomRow (collapsed box)', () => {
      const tree = {
        box1: {
          aboves: ['box2', 'box3'],
          belows: [],
          topRow: 20,
          bottomRow: 25,
          originalTopRow: 20,
          originalBottomRow: 25,
          distanceToNearestAbove: 0,
        },
        box2: {
          aboves: [],
          belows: ['box1'],
          topRow: 0,
          bottomRow: 15,
          originalTopRow: 0,
          originalBottomRow: 15,
          distanceToNearestAbove: 0,
        },
        box3: {
          aboves: [],
          belows: ['box1'],
          topRow: 5,
          bottomRow: 15,
          originalTopRow: 5,
          originalBottomRow: 15,
          distanceToNearestAbove: 0,
        },
      };
      const repositionedBoxes = {
        box2: { topRow: 10, bottomRow: 10 },
      };

      const result = getNearestAbove(tree, 'box1', repositionedBoxes);

      expect(result).toEqual(['box2', 'box3']);
    });

    test('should prefer collapsed box when both have same bottomRow', () => {
      const tree = {
        box1: {
          aboves: ['box2', 'box3'],
          belows: [],
          topRow: 20,
          bottomRow: 25,
          originalTopRow: 20,
          originalBottomRow: 25,
          distanceToNearestAbove: 0,
        },
        box2: {
          aboves: [],
          belows: ['box1'],
          topRow: 0,
          bottomRow: 15,
          originalTopRow: 0,
          originalBottomRow: 15,
          distanceToNearestAbove: 0,
        },
        box3: {
          aboves: [],
          belows: ['box1'],
          topRow: 5,
          bottomRow: 15,
          originalTopRow: 5,
          originalBottomRow: 15,
          distanceToNearestAbove: 0,
        },
      };
      const repositionedBoxes = {
        box3: { topRow: 15, bottomRow: 15 },
      };

      const result = getNearestAbove(tree, 'box1', repositionedBoxes);

      expect(result).toEqual(['box3']);  // 1.05μs -> 983ns (6.82% faster)
    });

    test('should handle zero bottomRow values', () => {
      const tree = {
        box1: {
          aboves: ['box2', 'box3'],
          belows: [],
          topRow: 20,
          bottomRow: 25,
          originalTopRow: 20,
          originalBottomRow: 25,
          distanceToNearestAbove: 0,
        },
        box2: {
          aboves: [],
          belows: ['box1'],
          topRow: 0,
          bottomRow: 0,
          originalTopRow: 0,
          originalBottomRow: 0,
          distanceToNearestAbove: 0,
        },
        box3: {
          aboves: [],
          belows: ['box1'],
          topRow: 5,
          bottomRow: 5,
          originalTopRow: 5,
          originalBottomRow: 5,
          distanceToNearestAbove: 0,
        },
      };
      const repositionedBoxes = {};

      const result = getNearestAbove(tree, 'box1', repositionedBoxes);

      expect(result).toEqual(['box3']);  // 991ns -> 1.00μs (1.20% slower)
    });

    test('should handle negative row values', () => {
      const tree = {
        box1: {
          aboves: ['box2', 'box3'],
          belows: [],
          topRow: 0,
          bottomRow: 5,
          originalTopRow: 0,
          originalBottomRow: 5,
          distanceToNearestAbove: 0,
        },
        box2: {
          aboves: [],
          belows: ['box1'],
          topRow: -10,
          bottomRow: -5,
          originalTopRow: -10,
          originalBottomRow: -5,
          distanceToNearestAbove: 0,
        },
        box3: {
          aboves: [],
          belows: ['box1'],
          topRow: -8,
          bottomRow: -2,
          originalTopRow: -8,
          originalBottomRow: -2,
          distanceToNearestAbove: 0,
        },
      };
      const repositionedBoxes = {};

      const result = getNearestAbove(tree, 'box1', repositionedBoxes);

      expect(result).toEqual(['box3']);  // 881ns -> 980ns (10.1% slower)
    });

    test('should handle large bottomRow values', () => {
      const tree = {
        box1: {
          aboves: ['box2', 'box3'],
          belows: [],
          topRow: 1000000,
          bottomRow: 1000005,
          originalTopRow: 1000000,
          originalBottomRow: 1000005,
          distanceToNearestAbove: 0,
        },
        box2: {
          aboves: [],
          belows: ['box1'],
          topRow: 0,
          bottomRow: 999999,
          originalTopRow: 0,
          originalBottomRow: 999999,
          distanceToNearestAbove: 0,
        },
        box3: {
          aboves: [],
          belows: ['box1'],
          topRow: 5,
          bottomRow: 999998,
          originalTopRow: 5,
          originalBottomRow: 999998,
          distanceToNearestAbove: 0,
        },
      };
      const repositionedBoxes = {};

      const result = getNearestAbove(tree, 'box1', repositionedBoxes);

      expect(result).toEqual(['box2']);  // 880ns -> 928ns (5.17% slower)
    });

    test('should handle single above box with repositioning', () => {
      const tree = {
        box1: {
          aboves: ['box2'],
          belows: [],
          topRow: 20,
          bottomRow: 25,
          originalTopRow: 20,
          originalBottomRow: 25,
          distanceToNearestAbove: 0,
        },
        box2: {
          aboves: [],
          belows: ['box1'],
          topRow: 0,
          bottomRow: 15,
          originalTopRow: 0,
          originalBottomRow: 15,
          distanceToNearestAbove: 0,
        },
      };
      const repositionedBoxes = {
        box2: { topRow: 5, bottomRow: 18 },
      };

      const result = getNearestAbove(tree, 'box1', repositionedBoxes);

      expect(result).toEqual(['box2']);  // 709ns -> 765ns (7.32% slower)
    });

    test('should handle all above boxes with same bottomRow and none collapsed', () => {
      const tree = {
        box1: {
          aboves: ['box2', 'box3', 'box4'],
          belows: [],
          topRow: 30,
          bottomRow: 35,
          originalTopRow: 30,
          originalBottomRow: 35,
          distanceToNearestAbove: 0,
        },
        box2: {
          aboves: [],
          belows: ['box1'],
          topRow: 0,
          bottomRow: 20,
          originalTopRow: 0,
          originalBottomRow: 20,
          distanceToNearestAbove: 0,
        },
        box3: {
          aboves: [],
          belows: ['box1'],
          topRow: 5,
          bottomRow: 20,
          originalTopRow: 5,
          originalBottomRow: 20,
          distanceToNearestAbove: 0,
        },
        box4: {
          aboves: [],
          belows: ['box1'],
          topRow: 10,
          bottomRow: 20,
          originalTopRow: 10,
          originalBottomRow: 20,
          distanceToNearestAbove: 0,
        },
      };
      const repositionedBoxes = {};

      const result = getNearestAbove(tree, 'box1', repositionedBoxes);

      expect(result.length).toBe(3);  // 1.26μs -> 1.09μs (16.0% faster)
      expect(result).toContain('box2');
      expect(result).toContain('box3');
      expect(result).toContain('box4');
    });

    test('should handle repositioned box that changes comparison result', () => {
      const tree = {
        box1: {
          aboves: ['box2', 'box3'],
          belows: [],
          topRow: 30,
          bottomRow: 35,
          originalTopRow: 30,
          originalBottomRow: 35,
          distanceToNearestAbove: 0,
        },
        box2: {
          aboves: [],
          belows: ['box1'],
          topRow: 0,
          bottomRow: 20,
          originalTopRow: 0,
          originalBottomRow: 20,
          distanceToNearestAbove: 0,
        },
        box3: {
          aboves: [],
          belows: ['box1'],
          topRow: 5,
          bottomRow: 22,
          originalTopRow: 5,
          originalBottomRow: 22,
          distanceToNearestAbove: 0,
        },
      };
      const repositionedBoxes = {
        box2: { topRow: 0, bottomRow: 25 },
      };

      const result = getNearestAbove(tree, 'box1', repositionedBoxes);

      expect(result).toEqual(['box2']);  // 884ns -> 856ns (3.27% faster)
    });
  });

  // ========== Large Scale Test Cases ==========
  describe('Performance tests', () => {
    test('should efficiently handle many above boxes', () => {
      const tree = {
        mainBox: {
          aboves: Array.from({ length: 100 }, (_, i) => `box${i}`),
          belows: [],
          topRow: 10000,
          bottomRow: 10005,
          originalTopRow: 10000,
          originalBottomRow: 10005,
          distanceToNearestAbove: 0,
        },
      };

      // Create above boxes with varying bottomRows
      Array.from({ length: 100 }, (_, i) => {
        tree[`box${i}`] = {
          aboves: [],
          belows: ['mainBox'],
          topRow: i * 10,
          bottomRow: i * 10 + 5 + Math.floor(i / 10),
          originalTopRow: i * 10,
          originalBottomRow: i * 10 + 5 + Math.floor(i / 10),
          distanceToNearestAbove: 0,
        };
      });

      const repositionedBoxes = {};
      const startTime = performance.now();

      const result = getNearestAbove(tree, 'mainBox', repositionedBoxes);

      const endTime = performance.now();

      expect(result.length).toBeGreaterThan(0);  // 10.8μs -> 11.2μs (4.16% slower)
      expect(endTime - startTime).toBeLessThan(1000); // Should complete in less than 1 second
    });

    test('should handle many repositioned boxes efficiently', () => {
      const tree = {
        mainBox: {
          aboves: Array.from({ length: 50 }, (_, i) => `box${i}`),
          belows: [],
          topRow: 5000,
          bottomRow: 5005,
          originalTopRow: 5000,
          originalBottomRow: 5005,
          distanceToNearestAbove: 0,
        },
      };

      Array.from({ length: 50 }, (_, i) => {
        tree[`box${i}`] = {
          aboves: [],
          belows: ['mainBox'],
          topRow: i * 20,
          bottomRow: i * 20 + 10,
          originalTopRow: i * 20,
          originalBottomRow: i * 20 + 10,
          distanceToNearestAbove: 0,
        };
      });

      const repositionedBoxes = {};
      Array.from({ length: 50 }, (_, i) => {
        repositionedBoxes[`box${i}`] = {
          topRow: i * 20,
          bottomRow: i * 20 + 15,
        };
      });

      const startTime = performance.now();

      const result = getNearestAbove(tree, 'mainBox', repositionedBoxes);

      const endTime = performance.now();

      expect(result.length).toBeGreaterThan(0);  // 7.65μs -> 6.19μs (23.5% faster)
      expect(endTime - startTime).toBeLessThan(1000);
    });

    test('should maintain correct behavior with many boxes at same bottomRow', () => {
      const tree = {
        mainBox: {
          aboves: Array.from({ length: 75 }, (_, i) => `box${i}`),
          belows: [],
          topRow: 1000,
          bottomRow: 1005,
          originalTopRow: 1000,
          originalBottomRow: 1005,
          distanceToNearestAbove: 0,
        },
      };

      Array.from({ length: 75 }, (_, i) => {
        tree[`box${i}`] = {
          aboves: [],
          belows: ['mainBox'],
          topRow: i,
          bottomRow: 900, // All have same bottomRow
          originalTopRow: i,
          originalBottomRow: 900,
          distanceToNearestAbove: 0,
        };
      });

      const repositionedBoxes = {};

      const result = getNearestAbove(tree, 'mainBox', repositionedBoxes);

      expect(result.length).toBe(75);  // 16.2μs -> 14.1μs (15.3% faster)
      Array.from({ length: 75 }, (_, i) => {
        expect(result).toContain(`box${i}`);
      });
    });

    test('should handle complex scenario with many boxes and repositioning', () => {
      const tree = {
        mainBox: {
          aboves: Array.from({ length: 80 }, (_, i) => `box${i}`),
          belows: [],
          topRow: 2000,
          bottomRow: 2005,
          originalTopRow: 2000,
          originalBottomRow: 2005,
          distanceToNearestAbove: 0,
        },
      };

      Array.from({ length: 80 }, (_, i) => {
        tree[`box${i}`] = {
          aboves: [],
          belows: ['mainBox'],
          topRow: i * 15,
          bottomRow: i * 15 + 8,
          originalTopRow: i * 15,
          originalBottomRow: i * 15 + 8,
          distanceToNearestAbove: 0,
        };
      });

      const repositionedBoxes = {};
      // Reposition every 4th box
      Array.from({ length: 20 }, (_, i) => {
        const boxIndex = i * 4;
        repositionedBoxes[`box${boxIndex}`] = {
          topRow: boxIndex * 15,
          bottomRow: boxIndex * 15 + 20,
        };
      });

      const startTime = performance.now();

      const result = getNearestAbove(tree, 'mainBox', repositionedBoxes);

      const endTime = performance.now();

      expect(result.length).toBeGreaterThan(0);  // 12.2μs -> 11.3μs (8.48% faster)
      expect(endTime - startTime).toBeLessThan(1000);
    });

    test('should correctly identify nearest when many boxes have consecutive bottomRows', () => {
      const tree = {
        mainBox: {
          aboves: Array.from({ length: 60 }, (_, i) => `box${i}`),
          belows: [],
          topRow: 3000,
          bottomRow: 3005,
          originalTopRow: 3000,
          originalBottomRow: 3005,
          distanceToNearestAbove: 0,
        },
      };

      Array.from({ length: 60 }, (_, i) => {
        tree[`box${i}`] = {
          aboves: [],
          belows: ['mainBox'],
          topRow: i * 5,
          bottomRow: 2900 + i, // Consecutive bottomRows
          originalTopRow: i * 5,
          originalBottomRow: 2900 + i,
          distanceToNearestAbove: 0,
        };
      });

      const repositionedBoxes = {};

      const result = getNearestAbove(tree, 'mainBox', repositionedBoxes);

      // Should only contain the box with highest bottomRow
      expect(result).toEqual(['box59']);  // 7.01μs -> 6.83μs (2.71% faster)
    });
  });
});

To edit these changes git checkout codeflash/optimize-getNearestAbove-ml1zpyxk and push.

Codeflash

The optimized code achieves a **44% runtime improvement** (198μs → 137μs) through strategic caching of `repositionedBoxes` lookups. This is a classic example of eliminating redundant object property accesses in a hot loop.

**What Changed:**
The optimization caches two frequently-accessed values at the beginning of each reduce iteration:
```typescript
const nextRepositioned = repositionedBoxes[next];
const prevRepositioned = repositionedBoxes[prev[0]];
```

**Why This Improves Performance:**
1. **Eliminates Redundant Lookups**: In the original code, `repositionedBoxes[next]` and `repositionedBoxes[prev[0]]` are accessed multiple times within the same iteration—first for checking existence, then for property access (`.bottomRow`, `.topRow`). Each object property lookup has a small cost that compounds in a reduce operation.

2. **JavaScript Object Access Cost**: Hash map lookups via bracket notation (`repositionedBoxes[key]`) are more expensive than variable reads. By performing the lookup once and storing the result, the optimization replaces 4-6 object accesses per iteration with 2 initial lookups plus fast variable reads.

3. **Cascading Effect in Reduce**: Since this runs in a `reduce()` over all `aboves` boxes, the savings multiply. Test results show dramatic improvements in large-scale scenarios:
   - 500 items: 88.5μs → 50.9μs (74% faster)
   - 300 items with ties: 32.0μs → 14.2μs (126% faster)
   - 100 items: 10.8μs → 11.2μs (modest 4% slower, likely noise)

**Best Performance Gains:**
The optimization excels when:
- **Many boxes exist** with repositioning data (50+ boxes: 23.5% faster)
- **Multiple boxes share the same bottomRow** requiring equality checks (300 items: 126% faster)
- **Cascading comparisons** occur where the same keys are checked repeatedly

**Impact on Workloads:**
Without `function_references`, we can't determine call frequency, but given this is in `autoHeight/helpers.ts` and handles box positioning logic, it likely runs during layout calculations—potentially multiple times per user interaction in UI frameworks. The 44% improvement could translate to smoother rendering in canvas/grid-based applications where many widgets need position recalculation.

The optimization is purely mechanical (caching repeated lookups) with no algorithmic changes, making it safe and predictable across all test scenarios.
@codeflash-ai codeflash-ai bot requested a review from misrasaurabh1 January 31, 2026 07:28
@codeflash-ai codeflash-ai bot added the ⚡️ codeflash Optimization PR opened by Codeflash AI label Jan 31, 2026
misrasaurabh1 added a commit to codeflash-ai/codeflash that referenced this pull request Jan 31, 2026
Type definitions (interfaces, types) that are found during context extraction
were being combined with read_only_context, which gets prepended to the target
code and becomes part of the code to be replaced. This caused the AI to include
these type definitions in the optimized output, duplicating imported types.

Fix:
- Add `type_definitions_context` field to CodeContext to keep type definitions
  separate from global variables
- Pass type definitions as `read_only_context_code` to the optimizer (true
  read-only context, not part of code to be replaced)
- Add tests to verify type definitions are properly separated

This fixes the bug where imported interfaces like `TreeNode` were being
duplicated in the optimization output even though they were already imported.

See: codeflash-ai/appsmith#20

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
misrasaurabh1 added a commit to codeflash-ai/codeflash that referenced this pull request Jan 31, 2026
…ment

When the optimized code contains type definitions (interfaces, types) that
are already imported in the original file, the code replacer was incorrectly
adding them as new declarations because it only checked for existing
declarations, not imports.

Fix: In `_add_global_declarations_for_language`, also check for imported
names (default imports, named imports, namespace imports) and exclude them
from being added as new declarations.

This fixes the bug where imported interfaces like `TreeNode` were being
duplicated in the output even though they were already imported.

See: codeflash-ai/appsmith#20

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
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