Skip to content

Comments

⚡️ Speed up method JavaScriptSupport._format_js_line_profile_output by 16% in PR #1561 (add/support_react)#1592

Merged
claude[bot] merged 2 commits intoadd/support_reactfrom
codeflash/optimize-pr1561-2026-02-20T08.39.24
Feb 20, 2026
Merged

⚡️ Speed up method JavaScriptSupport._format_js_line_profile_output by 16% in PR #1561 (add/support_react)#1592
claude[bot] merged 2 commits intoadd/support_reactfrom
codeflash/optimize-pr1561-2026-02-20T08.39.24

Conversation

@codeflash-ai
Copy link
Contributor

@codeflash-ai codeflash-ai bot commented Feb 20, 2026

⚡️ This pull request contains optimizations for PR #1561

If you approve this dependent PR, these changes will be merged into the original PR branch add/support_react.

This PR will be automatically closed if the original PR is merged.


📄 16% (0.16x) speedup for JavaScriptSupport._format_js_line_profile_output in codeflash/languages/javascript/support.py

⏱️ Runtime : 4.56 milliseconds 3.93 milliseconds (best of 225 runs)

📝 Explanation and details

The optimized code achieves a 15% runtime improvement (4.56ms → 3.93ms) through several targeted optimizations that reduce overhead in the formatting loop:

Key Performance Improvements:

  1. Pre-computed format strings - Moving format string definitions (header_format, data_format, separator) outside the loop eliminates redundant string parsing on every iteration, saving ~2% overhead per file.

  2. Division-to-multiplication optimization - The most impactful change: computing time_factor = 100.0 / total_time_ms once and using multiplication (pct = time_ms * time_factor) instead of division in the inner loop. This reduces the percentage calculation from 8.5% to 5.2% of runtime - a 42% speedup on this operation. Multiplication is significantly faster than division in CPU cycles.

  3. Direct dictionary access in sum() - Changed from data.get("time_ms", 0) to data["time_ms"] if "time_ms" in data, reducing method call overhead in the total time calculation (though this remains at ~10% of runtime).

  4. Cached timings lookup - Storing parsed_results.get("timings", {}) once avoids repeated dictionary lookups across iterations.

  5. str.format() over f-strings - While f-strings are generally fast, str.format() with pre-built format strings can be more efficient in tight loops with repeated formatting patterns, reducing the formatting overhead from 42.6% to 42.4% of total time.

Test Results Show Optimization Strength:

The speedup scales with data size - larger test cases see the most benefit:

  • test_large_scale_many_lines_produces_expected_number_of_output_rows: 18.5% faster (1.15ms → 973μs)
  • test_complex_large_scale: 18.4% faster (1.29ms → 1.09ms)
  • test_large_single_file: 15.1% faster (133μs → 116μs)
  • test_many_lines_per_file_100: 17.6% faster (126μs → 107μs)

This demonstrates the optimization is most valuable when formatting many profiling lines, which is the typical use case for line profiler output. The micro-optimizations compound effectively across iterations, making this change particularly beneficial for real-world JavaScript profiling scenarios with hundreds or thousands of lines.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 85 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Click to see Generated Regression Tests
import pytest  # used for our unit tests
from codeflash.languages.javascript.support import JavaScriptSupport

def test_empty_and_missing_timings_return_empty_string():
    """When parsed_results has no 'timings' key or it's empty, the function should return an empty string."""
    js = JavaScriptSupport()  # real instance of the class under test

    # Case 1: no 'timings' key at all
    codeflash_output = js._format_js_line_profile_output({}); result_missing = codeflash_output # 480ns -> 511ns (6.07% slower)

    # Case 2: 'timings' exists but is empty
    codeflash_output = js._format_js_line_profile_output({"timings": {}}); result_empty = codeflash_output # 320ns -> 321ns (0.312% slower)

def test_basic_formatting_single_file_two_lines():
    """Basic formatting: verifies header, file path, two formatted lines, and numeric formatting (3 decimals/time, 1 decimal percent)."""
    js = JavaScriptSupport()

    # Construct parsed results with two numeric line keys (ints)
    parsed = {
        "timings": {
            "a.js": {
                1: {"hits": 3, "time_ms": 10.0, "content": "x=1"},
                2: {"hits": 1, "time_ms": 30.0, "content": "y=2"},
            }
        }
    }

    codeflash_output = js._format_js_line_profile_output(parsed); output = codeflash_output # 12.4μs -> 12.2μs (1.73% faster)

    # The 80-dash separators should be present (two of them per file block)
    dash_line = "-" * 80

    # Verify ordering: line 1 should appear before line 2
    idx1 = output.find("\n     1")  # each data row starts with the right-aligned line number (6 width)
    idx2 = output.find("\n     2")

def test_truncation_of_long_content_shows_ellipsis_and_limited_length():
    """Content longer than 50 characters should be truncated to 47 chars + '...' (total 50 chars shown)."""
    js = JavaScriptSupport()

    long_content = "a" * 60  # 60 characters, definitely > 50
    parsed = {
        "timings": {
            "longfile.js": {
                10: {"hits": 1, "time_ms": 5.0, "content": long_content},
            }
        }
    }

    codeflash_output = js._format_js_line_profile_output(parsed); output = codeflash_output # 8.77μs -> 8.64μs (1.52% faster)

    # The truncated form should appear: first 47 characters then '...'
    expected_trunc = long_content[:47] + "..."

    # And the displayed content portion (after the percent) must be at most 50 characters (the truncated length)
    # Find the line for line number 10 and extract the content substring
    for line in output.splitlines():
        # look for the data row that starts with the padded line number
        if line.strip().startswith("10"):
            # Split off the content from the formatted columns by splitting on two spaces preceding the content
            # The function uses two spaces before content, so we can take the last token after "%  "
            if "%  " in line:
                displayed = line.split("%  ", 1)[1]
            else:
                # fallback: take last 50 characters
                displayed = line[-50:]
            break
    else:
        pytest.fail("Did not find line row for line number 10")

def test_zero_total_time_results_in_zero_percentages_and_zero_time_formatting():
    """When the total time across lines is zero, percent should be 0.0% for each line and time shown as 0.000."""
    js = JavaScriptSupport()

    parsed = {
        "timings": {
            "zero.js": {
                1: {"hits": 5, "time_ms": 0.0, "content": "noop"},
                2: {"hits": 2, "time_ms": 0.0, "content": "noop2"},
            }
        }
    }

    codeflash_output = js._format_js_line_profile_output(parsed); output = codeflash_output # 9.55μs -> 8.95μs (6.72% faster)

def test_string_line_keys_are_sorted_lexicographically():
    """If line keys are strings (not ints), they are sorted lexicographically by sorted(line_data.items())."""
    js = JavaScriptSupport()

    # Use string keys such that lexicographic order differs from numeric order
    parsed = {
        "timings": {
            "lex.js": {
                "2": {"hits": 1, "time_ms": 2.0, "content": "second"},
                "10": {"hits": 1, "time_ms": 10.0, "content": "tenth"},
            }
        }
    }

    codeflash_output = js._format_js_line_profile_output(parsed); output = codeflash_output # 10.1μs -> 9.46μs (6.56% faster)

    # For string keys, "10" should come before "2" lexicographically.
    idx_10 = output.find("\n    10")  # "10" right-aligned to width 6 creates leading spaces
    idx_2 = output.find("\n     2")

def test_large_scale_many_lines_produces_expected_number_of_output_rows():
    """Large-scale test: 1000 line entries should be handled and the output should contain the expected number of rows."""
    js = JavaScriptSupport()

    N = 1000  # number of lines to exercise large-scale behavior
    # Build a timings dict for a single file with N lines
    lines_data = {}
    # Each line gets time_ms = 1.0 and hits = 1 so total_time_ms = N
    for i in range(1, N + 1):
        lines_data[i] = {"hits": 1, "time_ms": 1.0, "content": f"line_{i}"}

    parsed = {"timings": {"big.js": lines_data}}

    codeflash_output = js._format_js_line_profile_output(parsed); output = codeflash_output # 1.15ms -> 973μs (18.5% faster)

    # The output should contain N data rows plus the 5 fixed header/file rows:
    # 1: "Line Profile Results:"
    # 2: "\nFile: big.js"
    # 3: dash line
    # 4: header labels
    # 5: dash line
    # Then N data rows follow.
    lines = output.splitlines()

    # Check that the first and last data rows are present and correctly formatted (first numeric line and last)
    # Find the data rows region start index (first occurrence of the header labels)
    header_idx = None
    for idx, ln in enumerate(lines):
        if "Time (ms)" in ln and "% Time" in ln:
            header_idx = idx
            break

    # The first data row should be at header_idx + 2 (since there's a dash line after header)
    first_data_row = lines[header_idx + 2]
    last_data_row = lines[-1]
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
import pytest
from codeflash.languages.javascript.frameworks.detector import FrameworkInfo
from codeflash.languages.javascript.support import JavaScriptSupport

def test_empty_parsed_results():
    """Test with empty parsed_results dict returns empty string."""
    support = JavaScriptSupport()
    codeflash_output = support._format_js_line_profile_output({}); result = codeflash_output # 461ns -> 480ns (3.96% slower)

def test_no_timings_key():
    """Test with parsed_results missing 'timings' key returns empty string."""
    support = JavaScriptSupport()
    codeflash_output = support._format_js_line_profile_output({"other_key": "value"}); result = codeflash_output # 360ns -> 430ns (16.3% slower)

def test_empty_timings():
    """Test with empty timings dict returns header but no file data."""
    support = JavaScriptSupport()
    codeflash_output = support._format_js_line_profile_output({"timings": {}}); result = codeflash_output # 450ns -> 450ns (0.000% faster)

def test_single_file_single_line():
    """Test with single file containing single line of profiling data."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "test.js": {
                1: {"hits": 5, "time_ms": 10.5, "content": "const x = 1;"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 9.58μs -> 9.56μs (0.209% faster)

def test_single_file_multiple_lines():
    """Test with single file containing multiple lines of profiling data."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "app.js": {
                1: {"hits": 10, "time_ms": 5.0, "content": "function foo() {"},
                2: {"hits": 10, "time_ms": 15.0, "content": "  return 42;"},
                3: {"hits": 10, "time_ms": 10.0, "content": "}"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 12.2μs -> 11.3μs (7.70% faster)

def test_multiple_files():
    """Test with multiple files in timings."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "file1.js": {
                1: {"hits": 1, "time_ms": 1.0, "content": "code1"}
            },
            "file2.js": {
                1: {"hits": 2, "time_ms": 2.0, "content": "code2"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 11.5μs -> 11.6μs (1.20% slower)

def test_line_content_truncation():
    """Test that long line content is truncated to 50 chars with ellipsis."""
    support = JavaScriptSupport()
    long_content = "a" * 60  # 60 character string
    parsed_results = {
        "timings": {
            "long.js": {
                1: {"hits": 1, "time_ms": 1.0, "content": long_content}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 7.75μs -> 7.55μs (2.65% faster)
    
    # Content should be truncated to 47 chars + "..."
    expected_content = "a" * 47 + "..."

def test_line_content_no_truncation():
    """Test that short line content is not truncated."""
    support = JavaScriptSupport()
    short_content = "console.log('hello');"
    parsed_results = {
        "timings": {
            "short.js": {
                1: {"hits": 1, "time_ms": 1.0, "content": short_content}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 7.25μs -> 7.10μs (2.13% faster)

def test_lines_sorted_numerically():
    """Test that line numbers are sorted in ascending order."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "sorted.js": {
                10: {"hits": 1, "time_ms": 1.0, "content": "line10"},
                5: {"hits": 1, "time_ms": 1.0, "content": "line5"},
                1: {"hits": 1, "time_ms": 1.0, "content": "line1"},
                20: {"hits": 1, "time_ms": 1.0, "content": "line20"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 12.9μs -> 12.0μs (7.44% faster)
    
    # Find positions of each line number in output
    pos_1 = result.find("1  ")
    pos_5 = result.find("5  ")
    pos_10 = result.find("10  ")
    pos_20 = result.find("20  ")

def test_zero_time_ms_percentage_calculation():
    """Test percentage calculation when total_time_ms is zero."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "zero.js": {
                1: {"hits": 5, "time_ms": 0.0, "content": "code"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 7.33μs -> 7.16μs (2.39% faster)

def test_missing_optional_fields():
    """Test handling of missing optional fields in line data."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "partial.js": {
                1: {},  # All fields missing
                2: {"hits": 1},  # Only hits
                3: {"time_ms": 5.0}  # Only time_ms
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 11.9μs -> 11.5μs (3.66% faster)

def test_zero_hits():
    """Test with zero hits on a line."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "zero_hits.js": {
                1: {"hits": 0, "time_ms": 0.5, "content": "unreachable"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 7.55μs -> 7.45μs (1.34% faster)

def test_large_hit_count():
    """Test with very large hit count."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "hot.js": {
                1: {"hits": 999999, "time_ms": 100.0, "content": "hotline"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 7.50μs -> 7.36μs (1.90% faster)

def test_formatting_alignment():
    """Test that output columns are properly aligned."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "align.js": {
                1: {"hits": 1, "time_ms": 1.111, "content": "a"},
                2: {"hits": 100, "time_ms": 22.222, "content": "bb"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 10.1μs -> 9.50μs (6.53% faster)
    
    lines = result.split("\n")
    # Find lines with data (after header)
    data_lines = [l for l in lines if l and l[0].isdigit()]

def test_output_structure():
    """Test the overall structure of the output."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "struct.js": {
                1: {"hits": 1, "time_ms": 1.0, "content": "test"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 7.39μs -> 7.29μs (1.37% faster)
    
    lines = result.split("\n")

def test_special_characters_in_content():
    """Test with special characters in line content."""
    support = JavaScriptSupport()
    special_content = "console.log('Hello\\nWorld \\t tab');"
    parsed_results = {
        "timings": {
            "special.js": {
                1: {"hits": 1, "time_ms": 1.0, "content": special_content}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 7.47μs -> 7.21μs (3.62% faster)

def test_unicode_in_content():
    """Test with unicode characters in line content."""
    support = JavaScriptSupport()
    unicode_content = "const emoji = '😀'; // 中文"
    parsed_results = {
        "timings": {
            "unicode.js": {
                1: {"hits": 1, "time_ms": 1.0, "content": unicode_content}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 8.57μs -> 8.62μs (0.580% slower)

def test_very_small_time_ms():
    """Test with very small time_ms values."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "tiny.js": {
                1: {"hits": 1, "time_ms": 0.001, "content": "fast"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 7.48μs -> 7.25μs (3.17% faster)

def test_very_large_time_ms():
    """Test with very large time_ms values."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "slow.js": {
                1: {"hits": 1, "time_ms": 999999.999, "content": "slowline"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 7.60μs -> 7.19μs (5.73% faster)

def test_exactly_50_char_content():
    """Test with content exactly 50 characters long."""
    support = JavaScriptSupport()
    exact_50 = "a" * 50
    parsed_results = {
        "timings": {
            "exact.js": {
                1: {"hits": 1, "time_ms": 1.0, "content": exact_50}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 7.42μs -> 7.18μs (3.34% faster)

def test_51_char_content():
    """Test with content exactly 51 characters long (first to be truncated)."""
    support = JavaScriptSupport()
    content_51 = "a" * 51
    parsed_results = {
        "timings": {
            "exact51.js": {
                1: {"hits": 1, "time_ms": 1.0, "content": content_51}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 7.64μs -> 7.65μs (0.144% slower)

def test_empty_line_content():
    """Test with empty string as line content."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "empty.js": {
                1: {"hits": 1, "time_ms": 1.0, "content": ""}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 7.23μs -> 7.06μs (2.42% faster)

def test_whitespace_only_content():
    """Test with whitespace-only line content."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "whitespace.js": {
                1: {"hits": 1, "time_ms": 1.0, "content": "    "}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 7.26μs -> 7.03μs (3.27% faster)

def test_negative_line_number():
    """Test with negative line number (edge case)."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "negative.js": {
                -1: {"hits": 1, "time_ms": 1.0, "content": "invalid"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 7.46μs -> 7.22μs (3.32% faster)

def test_very_large_line_number():
    """Test with very large line number."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "large_line.js": {
                999999: {"hits": 1, "time_ms": 1.0, "content": "far"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 7.45μs -> 7.32μs (1.79% faster)

def test_percentage_precision():
    """Test that percentages are formatted with 1 decimal place."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "precision.js": {
                1: {"hits": 1, "time_ms": 33.333, "content": "a"},
                2: {"hits": 1, "time_ms": 33.333, "content": "b"},
                3: {"hits": 1, "time_ms": 33.334, "content": "c"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 11.4μs -> 10.9μs (5.35% faster)

def test_floating_point_time_formatting():
    """Test floating point time values are formatted to 3 decimals."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "float.js": {
                1: {"hits": 1, "time_ms": 1.2345, "content": "test"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 8.06μs -> 7.88μs (2.30% faster)

def test_none_value_in_timings():
    """Test with None as a timing value."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "none_file.js": None
        }
    }
    # This might raise an error or be handled gracefully
    # Testing to ensure it doesn't crash
    try:
        codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output
    except (TypeError, AttributeError):
        # It's acceptable if this raises an error
        pass

def test_string_line_numbers():
    """Test with string keys instead of int line numbers."""
    support = JavaScriptSupport()
    parsed_results = {
        "timings": {
            "string_lines.js": {
                "1": {"hits": 1, "time_ms": 1.0, "content": "test"},
                "2": {"hits": 1, "time_ms": 1.0, "content": "test2"}
            }
        }
    }
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 10.6μs -> 10.4μs (1.84% faster)

def test_large_single_file():
    """Test with a single file containing many lines (100 lines)."""
    support = JavaScriptSupport()
    timings = {}
    for i in range(1, 101):
        timings[i] = {
            "hits": i,
            "time_ms": float(i),
            "content": f"line {i}"
        }
    
    parsed_results = {"timings": {"large.js": timings}}
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 133μs -> 116μs (15.1% faster)
    # Verify line count
    lines = result.split("\n")
    data_lines = [l for l in lines if l and l.strip()[0].isdigit()]

def test_many_files():
    """Test with many files (50 files)."""
    support = JavaScriptSupport()
    timings = {}
    for file_idx in range(1, 51):
        timings[f"file{file_idx}.js"] = {
            1: {"hits": file_idx, "time_ms": float(file_idx), "content": f"code{file_idx}"}
        }
    
    parsed_results = {"timings": timings}
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 134μs -> 123μs (9.38% faster)
    # Count file headers
    file_count = result.count("File:")

def test_complex_large_scale():
    """Test with large combined structure (20 files, 50 lines each)."""
    support = JavaScriptSupport()
    timings = {}
    for file_idx in range(1, 21):
        file_timings = {}
        for line_idx in range(1, 51):
            file_timings[line_idx] = {
                "hits": line_idx,
                "time_ms": float(line_idx) * 0.1,
                "content": f"f{file_idx}l{line_idx}"
            }
        timings[f"file{file_idx}.js"] = file_timings
    
    parsed_results = {"timings": timings}
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 1.29ms -> 1.09ms (18.4% faster)

def test_many_lines_per_file_100():
    """Test with 100 lines in a single file."""
    support = JavaScriptSupport()
    timings = {}
    for i in range(1, 101):
        timings[i] = {
            "hits": i % 10,
            "time_ms": (i % 10) * 1.5,
            "content": f"code line {i}"
        }
    
    parsed_results = {"timings": {"huge.js": timings}}
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 126μs -> 107μs (17.6% faster)
    
    lines = result.split("\n")
    data_lines = [l for l in lines if l and l.strip()[0].isdigit()]

def test_large_scale_with_truncation():
    """Test large file where many lines need truncation."""
    support = JavaScriptSupport()
    timings = {}
    long_content = "a" * 60
    for i in range(1, 51):
        timings[i] = {
            "hits": 1,
            "time_ms": 1.0,
            "content": long_content
        }
    
    parsed_results = {"timings": {"truncated.js": timings}}
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 73.0μs -> 63.2μs (15.5% faster)
    
    # Each line should be truncated
    truncated_content = "a" * 47 + "..."
    truncated_count = result.count(truncated_content)

def test_extreme_percentage_calculation():
    """Test percentage calculation with many lines and varying times."""
    support = JavaScriptSupport()
    timings = {}
    for i in range(1, 101):
        timings[i] = {
            "hits": 1,
            "time_ms": float(i),  # Total will be sum of 1 to 100 = 5050
            "content": f"line{i}"
        }
    
    parsed_results = {"timings": {"percentages.js": timings}}
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 130μs -> 115μs (13.6% faster)

def test_performance_with_1000_lines():
    """Test performance with 1000 lines in a single file."""
    support = JavaScriptSupport()
    timings = {}
    for i in range(1, 1001):
        timings[i] = {
            "hits": i % 100,
            "time_ms": float(i % 100) * 0.5,
            "content": f"line_{i:04d}"
        }
    
    parsed_results = {"timings": {"perf.js": timings}}
    codeflash_output = support._format_js_line_profile_output(parsed_results); result = codeflash_output # 1.25ms -> 1.08ms (15.0% faster)
    lines = result.split("\n")
    data_lines = [l for l in lines if l and l.strip()[0].isdigit()]
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.

To edit these changes git checkout codeflash/optimize-pr1561-2026-02-20T08.39.24 and push.

Codeflash Static Badge

The optimized code achieves a **15% runtime improvement** (4.56ms → 3.93ms) through several targeted optimizations that reduce overhead in the formatting loop:

**Key Performance Improvements:**

1. **Pre-computed format strings** - Moving format string definitions (`header_format`, `data_format`, `separator`) outside the loop eliminates redundant string parsing on every iteration, saving ~2% overhead per file.

2. **Division-to-multiplication optimization** - The most impactful change: computing `time_factor = 100.0 / total_time_ms` once and using multiplication (`pct = time_ms * time_factor`) instead of division in the inner loop. This reduces the percentage calculation from 8.5% to 5.2% of runtime - a **42% speedup** on this operation. Multiplication is significantly faster than division in CPU cycles.

3. **Direct dictionary access in sum()** - Changed from `data.get("time_ms", 0)` to `data["time_ms"] if "time_ms" in data`, reducing method call overhead in the total time calculation (though this remains at ~10% of runtime).

4. **Cached timings lookup** - Storing `parsed_results.get("timings", {})` once avoids repeated dictionary lookups across iterations.

5. **str.format() over f-strings** - While f-strings are generally fast, `str.format()` with pre-built format strings can be more efficient in tight loops with repeated formatting patterns, reducing the formatting overhead from 42.6% to 42.4% of total time.

**Test Results Show Optimization Strength:**

The speedup scales with data size - larger test cases see the most benefit:
- `test_large_scale_many_lines_produces_expected_number_of_output_rows`: **18.5% faster** (1.15ms → 973μs)
- `test_complex_large_scale`: **18.4% faster** (1.29ms → 1.09ms)  
- `test_large_single_file`: **15.1% faster** (133μs → 116μs)
- `test_many_lines_per_file_100`: **17.6% faster** (126μs → 107μs)

This demonstrates the optimization is most valuable when formatting many profiling lines, which is the typical use case for line profiler output. The micro-optimizations compound effectively across iterations, making this change particularly beneficial for real-world JavaScript profiling scenarios with hundreds or thousands of lines.
@codeflash-ai codeflash-ai bot added ⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: High Optimization Quality according to Codeflash labels Feb 20, 2026
Comment on lines 2286 to +2289
hits = data.get("hits", 0)
time_ms = data.get("time_ms", 0)
pct = (time_ms / total_time_ms * 100) if total_time_ms > 0 else 0
content = data.get("content", "")
# Truncate long lines for display
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: duplicate comment — "Truncate long lines for display" appears here and again at line 2294. The first one seems out of place (it's before the percentage calculation, not the truncation). Consider removing this one.

@claude
Copy link
Contributor

claude bot commented Feb 20, 2026

PR Review Summary

Prek Checks

Fixed - 12 auto-fixable issues resolved in codeflash/languages/javascript/support.py:

  • 7x W293 (blank-line-with-whitespace)
  • 5x Q000 (bad-quotes-inline-string)

Committed and pushed as style: auto-fix linting issues (39b67c6).

Mypy

No new mypy issues introduced. The PR actually reduces mypy errors in changed files from 37 → 26 (pre-existing errors on main).

Code Review

This is a codeflash optimization PR targeting _format_js_line_profile_output in support.py. The optimization is correct and safe:

  • Pre-computes format strings and separator outside the loop
  • Uses multiplication (time_ms * time_factor) instead of division per iteration
  • Switches from f-strings to pre-built .format() templates

Minor issue: Duplicate "Truncate long lines for display" comment (see inline comment).

No critical bugs, security issues, or breaking API changes found in the PR diff.

Test Coverage

PR branch (1 failure in unrelated test_tracer.py, 2409 passed):

File PR Stmts PR Miss PR Cover Main Cover Delta
codeflash/languages/javascript/support.py 1052 319 70% 71% -1%
codeflash/api/aiservice.py 363 290 20% 20% 0%
codeflash/languages/base.py 133 2 98% 98% 0%
codeflash/languages/javascript/parse.py 272 133 51% 49% +2%
codeflash/languages/javascript/treesitter.py 845 70 92% 92% 0%
codeflash/models/function_types.py 47 0 100% 100% 0%
codeflash/result/critic.py 100 27 73% 70% +3%
codeflash/result/explanation.py 84 46 45% 46% -1%
New: frameworks/detector.py 49 0 100% N/A New
New: frameworks/react/analyzer.py 62 0 100% N/A New
New: frameworks/react/benchmarking.py 41 0 100% N/A New
New: frameworks/react/context.py 119 1 99% N/A New
New: frameworks/react/discovery.py 128 8 94% N/A New
New: frameworks/react/profiler.py 129 112 13% N/A New ⚠️
New: frameworks/react/testgen.py 17 2 88% N/A New
TOTAL 3441 1010 71% 70% +1%

Notes:

  • Overall coverage increased by 1% (70% → 71%)
  • Most new React framework files have excellent coverage (94-100%)
  • profiler.py at 13% coverage is significantly below the 75% threshold for new files (most of the base branch, not this specific optimization PR)
  • The support.py -1% is within noise range and attributable to new lines added in the base branch
  • Test failure in test_tracer.py is pre-existing (also fails on main with 8 failures)

Last updated: 2026-02-20T09:00:00Z

@claude claude bot merged commit edd1c04 into add/support_react Feb 20, 2026
29 of 32 checks passed
@claude claude bot deleted the codeflash/optimize-pr1561-2026-02-20T08.39.24 branch February 20, 2026 12:47
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 🎯 Quality: High Optimization Quality according to Codeflash

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants