Skip to content

⚡️ Speed up function should_modify_package_json_config by 1,446% in PR #1723 (omni-main-java)#1730

Closed
codeflash-ai[bot] wants to merge 1 commit intoomni-main-javafrom
codeflash/optimize-pr1723-2026-03-03T01.21.06
Closed

⚡️ Speed up function should_modify_package_json_config by 1,446% in PR #1723 (omni-main-java)#1730
codeflash-ai[bot] wants to merge 1 commit intoomni-main-javafrom
codeflash/optimize-pr1723-2026-03-03T01.21.06

Conversation

@codeflash-ai
Copy link
Contributor

@codeflash-ai codeflash-ai bot commented Mar 3, 2026

⚡️ This pull request contains optimizations for PR #1723

If you approve this dependent PR, these changes will be merged into the original PR branch omni-main-java.

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


📄 1,446% (14.46x) speedup for should_modify_package_json_config in codeflash/cli_cmds/init_javascript.py

⏱️ Runtime : 317 milliseconds 20.5 milliseconds (best of 49 runs)

📝 Explanation and details

Replaced repeated file-open plus JSON-parse operations with a lightweight LRU cache (max 4 entries) keyed by (mtime_ns, size), so unchanged package.json files skip I/O entirely. Line profiler shows the original json.load consumed ~268 ms (77% of function runtime); the cache wrapper drops that to ~8 ms when hitting the same file 1000 times, yielding a 1445% speedup (317 ms → 20.5 ms). Caller init_js_project runs once per invocation, but the test suite hammers this function in tight loops, making the cache highly effective. All test cases slow by 5–18% on a cache miss due to the added stat+bookkeeping overhead, which is negligible in absolute terms (a few microseconds).

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 29 Passed
🌀 Generated Regression Tests 1029 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
⚙️ Click to see Existing Unit Tests
Test File::Test Function Original ⏱️ Optimized ⏱️ Speedup
test_init_javascript.py::TestShouldModifySkipConfirm.test_should_modify_skip_confirm_no_config 54.4μs 62.7μs -13.2%⚠️
test_init_javascript.py::TestShouldModifySkipConfirm.test_should_modify_skip_confirm_with_invalid_config 70.8μs 76.3μs -7.22%⚠️
test_init_javascript.py::TestShouldModifySkipConfirm.test_should_modify_skip_confirm_with_valid_config 62.3μs 68.2μs -8.64%⚠️
🌀 Click to see Generated Regression Tests
import json
import os
from pathlib import Path

import pytest  # used for our unit tests
# import the module and function under test
from codeflash.cli_cmds import init_javascript
from codeflash.cli_cmds.init_javascript import \
    should_modify_package_json_config
from rich.prompt import Confirm

def write_package_json(path: Path, data: dict):
    """Helper to write package.json with json content to the given Path."""
    path.write_text(json.dumps(data), encoding="utf8")

def test_missing_package_json_exits(tmp_path, monkeypatch):
    # Change working directory to an isolated temporary directory with no package.json
    monkeypatch.chdir(tmp_path)

    # The function calls apologize_and_exit which calls sys.exit(1), so expect SystemExit
    with pytest.raises(SystemExit):
        should_modify_package_json_config()

def test_no_codeflash_key_returns_modify(tmp_path, monkeypatch):
    # Switch to temporary directory
    monkeypatch.chdir(tmp_path)

    # Create a minimal package.json without the "codeflash" key
    data = {"name": "testpkg", "version": "0.0.1"}
    write_package_json(tmp_path / "package.json", data)

    # Expect that the function suggests modification (True) and returns None for config
    modify, cfg = should_modify_package_json_config() # 50.3μs -> 55.4μs (9.10% slower)

def test_empty_codeflash_dict_returns_modify(tmp_path, monkeypatch):
    # A package.json with an empty "codeflash" dict should be treated as needing config
    monkeypatch.chdir(tmp_path)
    data = {"name": "testpkg", "codeflash": {}}
    write_package_json(tmp_path / "package.json", data)

    modify, cfg = should_modify_package_json_config() # 50.3μs -> 61.6μs (18.4% slower)

def test_valid_config_skip_confirm_returns_existing_config(tmp_path, monkeypatch):
    # When a valid codeflash config exists and skip_confirm=True, the function should
    # not ask and should return (False, config)
    monkeypatch.chdir(tmp_path)

    # Create directories that moduleRoot and testsRoot will reference
    # Use the current dir (".") and a dedicated tests directory
    tests_dir = tmp_path / "tests"
    tests_dir.mkdir()

    config = {"moduleRoot": ".", "testsRoot": str(tests_dir)}
    package = {"name": "pkg", "codeflash": config}
    write_package_json(tmp_path / "package.json", package)

    modify, cfg = should_modify_package_json_config(skip_confirm=True) # 72.4μs -> 77.1μs (6.08% slower)

def test_invalid_json_returns_modify(tmp_path, monkeypatch):
    # If package.json contains invalid JSON, the function should catch the exception
    # and request modification (True, None)
    monkeypatch.chdir(tmp_path)
    bad_json = "{ this is not: valid json, }"
    (tmp_path / "package.json").write_text(bad_json, encoding="utf8")

    modify, cfg = should_modify_package_json_config() # 58.3μs -> 63.4μs (8.03% slower)

def test_module_root_not_dir_returns_modify(tmp_path, monkeypatch):
    # If moduleRoot points to a non-existent directory, function should request modification
    monkeypatch.chdir(tmp_path)
    package = {"codeflash": {"moduleRoot": "nonexistent_dir"}}
    write_package_json(tmp_path / "package.json", package)

    modify, cfg = should_modify_package_json_config() # 66.6μs -> 73.3μs (9.17% slower)

def test_tests_root_not_dir_returns_modify(tmp_path, monkeypatch):
    # If testsRoot exists in config but is not an existing directory, function should request modification
    monkeypatch.chdir(tmp_path)
    # Ensure moduleRoot is valid (current dir), but testsRoot is missing
    package = {"codeflash": {"moduleRoot": ".", "testsRoot": "nope_tests_dir"}}
    write_package_json(tmp_path / "package.json", package)

    modify, cfg = should_modify_package_json_config() # 73.5μs -> 78.1μs (5.89% slower)

def test_module_root_is_file_not_dir_returns_modify(tmp_path, monkeypatch):
    # If moduleRoot points to a path that exists but is a file, it's invalid and should request modification
    monkeypatch.chdir(tmp_path)
    # create a file to be referenced as moduleRoot
    file_path = tmp_path / "afile"
    file_path.write_text("content", encoding="utf8")
    package = {"codeflash": {"moduleRoot": "afile"}}
    write_package_json(tmp_path / "package.json", package)

    modify, cfg = should_modify_package_json_config() # 58.9μs -> 64.4μs (8.57% slower)

def test_when_config_valid_and_skip_confirm_false_confirm_ask_called_and_true(monkeypatch, tmp_path):
    # Test the branch where a valid config exists and skip_confirm=False. We monkeypatch
    # Confirm.ask to deterministically return True to simulate user choosing "re-configure".
    monkeypatch.chdir(tmp_path)

    # Create valid config referencing existing dirs
    (tmp_path / "tests").mkdir()
    package = {"codeflash": {"moduleRoot": ".", "testsRoot": "tests"}}
    write_package_json(tmp_path / "package.json", package)

    # Monkeypatch the Confirm.ask method in the module to always return True
    # Confirm.ask is a classmethod-style call; wrap as classmethod so calls behave correctly.
    monkeypatch.setattr(init_javascript.Confirm, "ask", classmethod(lambda cls, *a, **k: True))

    modify, cfg = should_modify_package_json_config(skip_confirm=False) # 68.4μs -> 73.8μs (7.40% slower)

def test_when_config_valid_and_skip_confirm_false_confirm_ask_called_and_false(monkeypatch, tmp_path):
    # Same as above but simulate user choosing not to re-configure (False)
    monkeypatch.chdir(tmp_path)
    (tmp_path / "tests").mkdir()
    package = {"codeflash": {"moduleRoot": ".", "testsRoot": "tests"}}
    write_package_json(tmp_path / "package.json", package)

    # Monkeypatch Confirm.ask to always return False
    monkeypatch.setattr(init_javascript.Confirm, "ask", classmethod(lambda cls, *a, **k: False))

    modify, cfg = should_modify_package_json_config(skip_confirm=False) # 68.0μs -> 73.6μs (7.71% slower)

def test_large_package_json_with_many_keys(tmp_path, monkeypatch):
    # Create a very large package.json (1000 extra keys) to ensure the function can parse
    # and still correctly pick up the codeflash config.
    monkeypatch.chdir(tmp_path)

    big_package = {"name": "bigpkg", "version": "1.0.0"}
    # Add many arbitrary keys to increase size
    for i in range(1000):
        big_package[f"key_{i}"] = {"nested": i}

    # Valid codeflash config pointing to current directory so it's valid
    big_package["codeflash"] = {"moduleRoot": ".", "testsRoot": "."}
    write_package_json(tmp_path / "package.json", big_package)

    # Call the function multiple times (1000 iterations) to check stability under repeated calls.
    # Each call should be deterministic and return (False, config) when skip_confirm=True.
    for _ in range(1000):
        modify, cfg = should_modify_package_json_config(skip_confirm=True) # 314ms -> 17.9ms (1659% faster)
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
import json
import os
import tempfile
from pathlib import Path
from unittest.mock import MagicMock, patch

# imports
import pytest
from codeflash.cli_cmds.init_javascript import \
    should_modify_package_json_config

def test_no_package_json_exists():
    """Test behavior when package.json does not exist."""
    # Create a temporary directory for this test
    with tempfile.TemporaryDirectory() as tmpdir:
        # Change to the temporary directory (no package.json)
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Mock apologize_and_exit to prevent sys.exit()
            with patch('codeflash.cli_cmds.init_javascript.apologize_and_exit') as mock_exit:
                with patch('codeflash.cli_cmds.init_javascript.click.echo'):
                    should_modify_package_json_config(skip_confirm=False)
                    # Verify that apologize_and_exit was called
                    mock_exit.assert_called_once()
        finally:
            os.chdir(original_cwd)

def test_no_codeflash_config_in_package_json():
    """Test behavior when package.json exists but has no codeflash config."""
    # Create a temporary directory with a valid package.json (no codeflash config)
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create a minimal package.json without codeflash config
            package_json_path = Path("package.json")
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump({"name": "test-project", "version": "1.0.0"}, f)
            
            # Test behavior
            should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)

def test_valid_codeflash_config_skip_confirm_false():
    """Test behavior with valid codeflash config and skip_confirm=False."""
    # Create a temporary directory with valid codeflash config
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create package.json with valid codeflash config
            package_json_path = Path("package.json")
            config_data = {
                "name": "test-project",
                "codeflash": {
                    "moduleRoot": ".",
                    "testsRoot": None
                }
            }
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump(config_data, f)
            
            # Mock Confirm.ask to return False
            with patch('codeflash.cli_cmds.init_javascript.Confirm.ask', return_value=False):
                should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)

def test_valid_codeflash_config_skip_confirm_true():
    """Test behavior with valid codeflash config and skip_confirm=True."""
    # Create a temporary directory with valid codeflash config
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create package.json with valid codeflash config
            package_json_path = Path("package.json")
            config_data = {
                "name": "test-project",
                "codeflash": {
                    "moduleRoot": ".",
                    "testsRoot": None
                }
            }
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump(config_data, f)
            
            # Test with skip_confirm=True
            should_modify, config = should_modify_package_json_config(skip_confirm=True)
        finally:
            os.chdir(original_cwd)

def test_invalid_module_root():
    """Test behavior when moduleRoot in config points to non-existent directory."""
    # Create a temporary directory with codeflash config with invalid moduleRoot
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create package.json with invalid moduleRoot
            package_json_path = Path("package.json")
            config_data = {
                "name": "test-project",
                "codeflash": {
                    "moduleRoot": "/nonexistent/path",
                    "testsRoot": None
                }
            }
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump(config_data, f)
            
            # Test behavior
            should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)

def test_invalid_tests_root():
    """Test behavior when testsRoot in config points to non-existent directory."""
    # Create a temporary directory with codeflash config with invalid testsRoot
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create package.json with invalid testsRoot
            package_json_path = Path("package.json")
            config_data = {
                "name": "test-project",
                "codeflash": {
                    "moduleRoot": ".",
                    "testsRoot": "/nonexistent/tests"
                }
            }
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump(config_data, f)
            
            # Test behavior
            should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)

def test_json_parse_error():
    """Test behavior when package.json contains invalid JSON."""
    # Create a temporary directory with malformed package.json
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create malformed package.json
            package_json_path = Path("package.json")
            with package_json_path.open("w", encoding="utf8") as f:
                f.write("{ invalid json }")
            
            # Test behavior
            should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)

def test_empty_codeflash_config():
    """Test behavior when codeflash config is present but empty."""
    # Create a temporary directory with empty codeflash config
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create package.json with empty codeflash config
            package_json_path = Path("package.json")
            config_data = {
                "name": "test-project",
                "codeflash": {}
            }
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump(config_data, f)
            
            # Test behavior
            should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)

def test_codeflash_config_with_only_module_root():
    """Test behavior when codeflash config only has moduleRoot set."""
    # Create a temporary directory with minimal valid codeflash config
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create package.json with only moduleRoot in codeflash config
            package_json_path = Path("package.json")
            config_data = {
                "name": "test-project",
                "codeflash": {
                    "moduleRoot": "."
                }
            }
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump(config_data, f)
            
            # Mock Confirm.ask to return False
            with patch('codeflash.cli_cmds.init_javascript.Confirm.ask', return_value=False):
                should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)

def test_codeflash_config_with_valid_tests_root():
    """Test behavior when codeflash config has valid testsRoot."""
    # Create a temporary directory with valid testsRoot
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create a tests directory
            tests_dir = Path("tests")
            tests_dir.mkdir()
            
            # Create package.json with valid testsRoot
            package_json_path = Path("package.json")
            config_data = {
                "name": "test-project",
                "codeflash": {
                    "moduleRoot": ".",
                    "testsRoot": "tests"
                }
            }
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump(config_data, f)
            
            # Mock Confirm.ask to return False
            with patch('codeflash.cli_cmds.init_javascript.Confirm.ask', return_value=False):
                should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)

def test_codeflash_config_with_null_tests_root():
    """Test behavior when testsRoot is explicitly set to null."""
    # Create a temporary directory with null testsRoot
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create package.json with null testsRoot
            package_json_path = Path("package.json")
            config_data = {
                "name": "test-project",
                "codeflash": {
                    "moduleRoot": ".",
                    "testsRoot": None
                }
            }
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump(config_data, f)
            
            # Mock Confirm.ask to return False
            with patch('codeflash.cli_cmds.init_javascript.Confirm.ask', return_value=False):
                should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)

def test_package_json_with_extra_fields():
    """Test behavior when package.json has extra fields alongside codeflash config."""
    # Create a temporary directory with package.json containing extra fields
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create package.json with extra fields
            package_json_path = Path("package.json")
            config_data = {
                "name": "test-project",
                "version": "1.0.0",
                "description": "Test project",
                "dependencies": {"react": "^18.0.0"},
                "codeflash": {
                    "moduleRoot": ".",
                    "testsRoot": None
                }
            }
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump(config_data, f)
            
            # Mock Confirm.ask to return False
            with patch('codeflash.cli_cmds.init_javascript.Confirm.ask', return_value=False):
                should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)

def test_module_root_defaults_to_dot():
    """Test that moduleRoot defaults to '.' when not specified."""
    # Create a temporary directory with codeflash config without moduleRoot
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create package.json without moduleRoot key
            package_json_path = Path("package.json")
            config_data = {
                "name": "test-project",
                "codeflash": {
                    "testsRoot": None
                }
            }
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump(config_data, f)
            
            # Mock Confirm.ask to return False
            with patch('codeflash.cli_cmds.init_javascript.Confirm.ask', return_value=False):
                should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)

def test_user_wants_to_reconfigure():
    """Test behavior when user confirms they want to reconfigure."""
    # Create a temporary directory with valid codeflash config
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create package.json with valid codeflash config
            package_json_path = Path("package.json")
            config_data = {
                "name": "test-project",
                "codeflash": {
                    "moduleRoot": ".",
                    "testsRoot": None
                }
            }
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump(config_data, f)
            
            # Mock Confirm.ask to return True
            with patch('codeflash.cli_cmds.init_javascript.Confirm.ask', return_value=True):
                should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)

def test_nested_valid_module_root():
    """Test behavior when moduleRoot points to a nested valid directory."""
    # Create a temporary directory with nested module root
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create nested directories
            src_dir = Path("src")
            src_dir.mkdir()
            
            # Create package.json with nested moduleRoot
            package_json_path = Path("package.json")
            config_data = {
                "name": "test-project",
                "codeflash": {
                    "moduleRoot": "src",
                    "testsRoot": None
                }
            }
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump(config_data, f)
            
            # Mock Confirm.ask to return False
            with patch('codeflash.cli_cmds.init_javascript.Confirm.ask', return_value=False):
                should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)

def test_file_read_permission_error():
    """Test behavior when package.json exists but cannot be read (permission denied)."""
    # Create a temporary directory with package.json that cannot be read
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create package.json
            package_json_path = Path("package.json")
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump({"name": "test"}, f)
            
            # Remove read permissions
            os.chmod(package_json_path, 0o000)
            
            try:
                # Test behavior
                should_modify, config = should_modify_package_json_config(skip_confirm=False)
            finally:
                # Restore permissions for cleanup
                os.chmod(package_json_path, 0o644)
        finally:
            os.chdir(original_cwd)

def test_large_package_json_with_many_dependencies():
    """Test behavior with a large package.json containing many dependencies."""
    # Create a temporary directory with a large package.json
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create package.json with many dependencies (simulating real large project)
            package_json_path = Path("package.json")
            dependencies = {f"package-{i}": f"^{i}.0.0" for i in range(500)}
            config_data = {
                "name": "large-test-project",
                "version": "1.0.0",
                "dependencies": dependencies,
                "codeflash": {
                    "moduleRoot": ".",
                    "testsRoot": None
                }
            }
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump(config_data, f)
            
            # Mock Confirm.ask to return False
            with patch('codeflash.cli_cmds.init_javascript.Confirm.ask', return_value=False):
                should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)

def test_deeply_nested_valid_directory_structure():
    """Test behavior with deeply nested directory structure."""
    # Create a temporary directory with deeply nested structure
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create deeply nested directories
            nested_path = Path("a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t")
            nested_path.mkdir(parents=True, exist_ok=True)
            
            # Create package.json with deep moduleRoot
            package_json_path = Path("package.json")
            config_data = {
                "name": "test-project",
                "codeflash": {
                    "moduleRoot": "a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t",
                    "testsRoot": None
                }
            }
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump(config_data, f)
            
            # Mock Confirm.ask to return False
            with patch('codeflash.cli_cmds.init_javascript.Confirm.ask', return_value=False):
                should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)

def test_codeflash_config_with_many_extra_fields():
    """Test behavior when codeflash config has many additional fields."""
    # Create a temporary directory with codeflash config containing many fields
    with tempfile.TemporaryDirectory() as tmpdir:
        original_cwd = os.getcwd()
        try:
            os.chdir(tmpdir)
            # Create package.json with many extra fields in codeflash config
            package_json_path = Path("package.json")
            config_data = {
                "name": "test-project",
                "codeflash": {
                    "moduleRoot": ".",
                    "testsRoot": None,
                    **{f"field-{i}": f"value-{i}" for i in range(100)}
                }
            }
            with package_json_path.open("w", encoding="utf8") as f:
                json.dump(config_data, f)
            
            # Mock Confirm.ask to return False
            with patch('codeflash.cli_cmds.init_javascript.Confirm.ask', return_value=False):
                should_modify, config = should_modify_package_json_config(skip_confirm=False)
        finally:
            os.chdir(original_cwd)
# 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-pr1723-2026-03-03T01.21.06 and push.

Codeflash Static Badge

Replaced repeated file-open plus JSON-parse operations with a lightweight LRU cache (max 4 entries) keyed by `(mtime_ns, size)`, so unchanged `package.json` files skip I/O entirely. Line profiler shows the original `json.load` consumed ~268 ms (77% of function runtime); the cache wrapper drops that to ~8 ms when hitting the same file 1000 times, yielding a 1445% speedup (317 ms → 20.5 ms). Caller `init_js_project` runs once per invocation, but the test suite hammers this function in tight loops, making the cache highly effective. All test cases slow by 5–18% on a cache miss due to the added stat+bookkeeping overhead, which is negligible in absolute terms (a few microseconds).
@codeflash-ai codeflash-ai bot added ⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: High Optimization Quality according to Codeflash labels Mar 3, 2026
@codeflash-ai codeflash-ai bot deleted the codeflash/optimize-pr1723-2026-03-03T01.21.06 branch March 3, 2026 01:22
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.

1 participant