Skip to content

Conversation

@codeflash-ai
Copy link

@codeflash-ai codeflash-ai bot commented Dec 4, 2025

📄 9% (0.09x) speedup for get_default_chrome_location in skyvern/cli/browser.py

⏱️ Runtime : 512 microseconds 471 microseconds (best of 131 runs)

📝 Explanation and details

The optimization changes the chrome_paths list to a tuple in the Linux branch of the function. This simple change provides an 8% speedup by leveraging Python's more efficient tuple implementation.

Key optimization:

  • List to tuple conversion: Changed chrome_paths = ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"] to chrome_paths = ("/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser")

Why this improves performance:

  1. Faster object creation: Tuples are immutable and have less overhead during construction than lists
  2. Memory efficiency: Tuples use slightly less memory per object compared to lists
  3. Reduced allocation time: The profiler shows the tuple assignment takes ~246ns vs ~276.5ns for the list (11% faster on that line)

Impact on workloads:
Based on the function reference, this function is called from setup_browser_config() during browser configuration setup. While not in a tight loop, the optimization provides measurable gains for:

  • Linux systems: Where the function iterates through Chrome paths using os.path.exists() calls
  • Test cases involving Linux: Show 8-26% improvements in scenarios where multiple path checks are performed

Test case performance:
The optimization particularly benefits Linux-specific test cases:

  • Cases with no existing paths: 17-18% faster
  • Cases finding paths early in the sequence: 13-15% faster
  • Repeated calls on Linux systems: 10-12% faster

Since the data structure is never modified (only iterated), using a tuple is semantically appropriate and provides free performance gains with zero behavioral changes.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 2635 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Generated Regression Tests and Runtime
import os

# imports
import pytest  # used for our unit tests
from skyvern.cli.browser import get_default_chrome_location

# unit tests

# ---- Basic Test Cases ----

def test_darwin_returns_mac_path():
    """Test that 'darwin' returns the correct macOS Chrome path."""
    codeflash_output = get_default_chrome_location("darwin"); result = codeflash_output # 408ns -> 414ns (1.45% slower)

def test_linux_returns_google_chrome_if_none_exist(monkeypatch):
    """
    Test that 'linux' returns '/usr/bin/google-chrome' if none of the candidate paths exist.
    """
    # Patch os.path.exists to always return False
    monkeypatch.setattr(os.path, "exists", lambda path: False)
    codeflash_output = get_default_chrome_location("linux"); result = codeflash_output # 872ns -> 740ns (17.8% faster)

def test_linux_returns_first_existing_path(monkeypatch):
    """
    Test that 'linux' returns the first existing path from the candidate list.
    """
    # Simulate only '/usr/bin/chromium' exists
    def fake_exists(path):
        return path == "/usr/bin/chromium"
    monkeypatch.setattr(os.path, "exists", fake_exists)
    codeflash_output = get_default_chrome_location("linux"); result = codeflash_output # 1.01μs -> 882ns (15.0% faster)

def test_linux_returns_chromium_browser_if_only_that_exists(monkeypatch):
    """
    Test that 'linux' returns '/usr/bin/chromium-browser' if only that exists.
    """
    def fake_exists(path):
        return path == "/usr/bin/chromium-browser"
    monkeypatch.setattr(os.path, "exists", fake_exists)
    codeflash_output = get_default_chrome_location("linux"); result = codeflash_output # 958ns -> 832ns (15.1% faster)

def test_wsl_returns_windows_path():
    """Test that 'wsl' returns the correct Windows path for Chrome."""
    codeflash_output = get_default_chrome_location("wsl"); result = codeflash_output # 386ns -> 372ns (3.76% faster)

def test_windows_returns_windows_path():
    """Test that 'windows' returns the correct Windows path for Chrome."""
    codeflash_output = get_default_chrome_location("windows"); result = codeflash_output # 377ns -> 368ns (2.45% faster)

def test_unknown_os_returns_windows_path():
    """Test that an unknown OS string returns the Windows path."""
    codeflash_output = get_default_chrome_location("plan9"); result = codeflash_output # 425ns -> 447ns (4.92% slower)

# ---- Edge Test Cases ----

def test_case_sensitivity():
    """Test that the function is case-sensitive for host_system."""
    # Should not match 'Darwin', 'LINUX', etc.
    codeflash_output = get_default_chrome_location("Darwin") # 446ns -> 436ns (2.29% faster)
    codeflash_output = get_default_chrome_location("LINUX") # 278ns -> 289ns (3.81% slower)

def test_empty_string_returns_windows_path():
    """Test that an empty string returns the Windows path."""
    codeflash_output = get_default_chrome_location("") # 305ns -> 305ns (0.000% faster)

def test_linux_all_paths_exist(monkeypatch):
    """Test that if all candidate paths exist, the first is returned."""
    monkeypatch.setattr(os.path, "exists", lambda path: True)
    codeflash_output = get_default_chrome_location("linux"); result = codeflash_output # 1.07μs -> 849ns (25.8% faster)

def test_linux_paths_exist_out_of_order(monkeypatch):
    """Test that only the first path in the list is returned even if all exist."""
    # Simulate all exist, but order is enforced
    monkeypatch.setattr(os.path, "exists", lambda path: True)
    codeflash_output = get_default_chrome_location("linux"); result = codeflash_output # 824ns -> 718ns (14.8% faster)

def test_linux_second_path_exists(monkeypatch):
    """Test that if only the second path exists, it is returned."""
    monkeypatch.setattr(os.path, "exists", lambda path: path == "/usr/bin/chromium")
    codeflash_output = get_default_chrome_location("linux"); result = codeflash_output # 1.05μs -> 954ns (9.96% faster)

def test_linux_no_os_path(monkeypatch):
    """Test that a non-linux, non-darwin, non-wsl returns the Windows path."""
    monkeypatch.setattr(os.path, "exists", lambda path: False)
    codeflash_output = get_default_chrome_location("solaris"); result = codeflash_output # 418ns -> 428ns (2.34% slower)

def test_linux_path_with_trailing_spaces(monkeypatch):
    """Test that 'linux ' (with trailing space) returns Windows path."""
    monkeypatch.setattr(os.path, "exists", lambda path: False)
    codeflash_output = get_default_chrome_location("linux "); result = codeflash_output # 405ns -> 433ns (6.47% slower)

# ---- Large Scale Test Cases ----

@pytest.mark.parametrize("os_name", [f"linux_{i}" for i in range(100)])
def test_many_unknown_os_names_return_windows_path(os_name):
    """Test that many unknown OS names return the Windows path (scalability)."""
    codeflash_output = get_default_chrome_location(os_name) # 33.1μs -> 31.9μs (3.86% faster)

def test_linux_many_paths(monkeypatch):
    """
    Test performance with a large number of candidate paths, only the first exists.
    This simulates what would happen if the candidate list grew.
    """
    # Patch the function to use a long list of paths
    original_func = get_default_chrome_location.__code__
    long_paths = [f"/usr/bin/chrome_{i}" for i in range(1000)]
    long_paths[0] = "/usr/bin/google-chrome"

    def fake_exists(path):
        return path == "/usr/bin/google-chrome"

    # Create a custom function for this test
    def custom_get_default_chrome_location(host_system: str) -> str:
        if host_system == "linux":
            for path in long_paths:
                if fake_exists(path):
                    return path
            return "/usr/bin/google-chrome"
        return get_default_chrome_location(host_system)

    # Test that the first path is returned efficiently
    result = custom_get_default_chrome_location("linux")

def test_linux_large_scale_last_path_exists(monkeypatch):
    """
    Test that if only the last path in a large candidate list exists, it is found.
    """
    long_paths = [f"/usr/bin/chrome_{i}" for i in range(999)]
    long_paths.append("/usr/bin/google-chrome")

    def fake_exists(path):
        return path == "/usr/bin/google-chrome"

    def custom_get_default_chrome_location(host_system: str) -> str:
        if host_system == "linux":
            for path in long_paths:
                if fake_exists(path):
                    return path
            return "/usr/bin/google-chrome"
        return get_default_chrome_location(host_system)

    result = custom_get_default_chrome_location("linux")

def test_performance_many_calls(monkeypatch):
    """
    Test that calling the function many times does not degrade performance or leak memory.
    """
    monkeypatch.setattr(os.path, "exists", lambda path: False)
    for _ in range(500):
        codeflash_output = get_default_chrome_location("linux") # 121μs -> 109μs (10.7% faster)
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
import os

# imports
import pytest  # used for our unit tests
from skyvern.cli.browser import get_default_chrome_location

# unit tests

# Basic Test Cases

def test_darwin_returns_mac_path():
    # Test for macOS ("darwin") system
    codeflash_output = get_default_chrome_location("darwin") # 322ns -> 372ns (13.4% slower)

def test_wsl_returns_wsl_path():
    # Test for WSL system
    codeflash_output = get_default_chrome_location("wsl") # 378ns -> 404ns (6.44% slower)

def test_windows_returns_windows_path():
    # Test for Windows system (catch-all)
    codeflash_output = get_default_chrome_location("windows") # 389ns -> 375ns (3.73% faster)

def test_unknown_os_returns_windows_path():
    # Test for an unknown OS string, should default to Windows path
    codeflash_output = get_default_chrome_location("solaris") # 374ns -> 353ns (5.95% faster)

# Edge Test Cases

def test_linux_returns_first_existing_path(monkeypatch):
    # Test for linux: if multiple paths exist, should return the first one found
    paths = ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"]
    # Simulate os.path.exists for each path
    def fake_exists(path):
        # Only the second path exists
        return path == "/usr/bin/chromium"
    monkeypatch.setattr(os.path, "exists", fake_exists)
    codeflash_output = get_default_chrome_location("linux") # 1.09μs -> 980ns (11.5% faster)

def test_linux_returns_google_chrome_if_none_exist(monkeypatch):
    # Test for linux: if none of the paths exist, should return google-chrome path
    def fake_exists(path):
        return False
    monkeypatch.setattr(os.path, "exists", fake_exists)
    codeflash_output = get_default_chrome_location("linux") # 897ns -> 758ns (18.3% faster)

def test_linux_returns_first_path_if_multiple_exist(monkeypatch):
    # If multiple paths exist, should return the first one in the list
    def fake_exists(path):
        return path in ["/usr/bin/google-chrome", "/usr/bin/chromium"]
    monkeypatch.setattr(os.path, "exists", fake_exists)
    codeflash_output = get_default_chrome_location("linux") # 895ns -> 775ns (15.5% faster)

def test_linux_returns_chromium_browser_if_only_third_exists(monkeypatch):
    # Only the third path exists
    def fake_exists(path):
        return path == "/usr/bin/chromium-browser"
    monkeypatch.setattr(os.path, "exists", fake_exists)
    codeflash_output = get_default_chrome_location("linux") # 1.06μs -> 885ns (19.9% faster)

@pytest.mark.parametrize("input_os", ["", None, "mac", "win32", "ubuntu", "BSD"])
def test_various_unknown_os_returns_windows_path(input_os):
    # All unknown OS strings should default to Windows path
    codeflash_output = get_default_chrome_location(input_os) # 2.62μs -> 2.56μs (2.11% faster)

def test_case_sensitivity_of_os_string():
    # "Darwin" (capitalized) should not match "darwin" and thus default to Windows path
    codeflash_output = get_default_chrome_location("Darwin") # 451ns -> 443ns (1.81% faster)

def test_linux_path_not_returned_for_non_linux(monkeypatch):
    # Even if os.path.exists returns True, non-linux OS should not return linux path
    monkeypatch.setattr(os.path, "exists", lambda path: True)
    codeflash_output = get_default_chrome_location("darwin") # 320ns -> 330ns (3.03% slower)
    codeflash_output = get_default_chrome_location("wsl") # 254ns -> 280ns (9.29% slower)
    codeflash_output = get_default_chrome_location("windows") # 160ns -> 151ns (5.96% faster)

# Large Scale Test Cases

def test_large_number_of_linux_checks(monkeypatch):
    # Simulate a system where none of the chrome paths exist, many calls to os.path.exists
    call_count = {"count": 0}
    def fake_exists(path):
        call_count["count"] += 1
        return False
    monkeypatch.setattr(os.path, "exists", fake_exists)
    # Should still return the default path and not fail
    codeflash_output = get_default_chrome_location("linux"); result = codeflash_output # 1.28μs -> 1.18μs (8.39% faster)

def test_massive_unknown_os_inputs():
    # Test scalability: run the function on a large number of unknown OS inputs
    for i in range(1000):
        os_name = f"unknown_os_{i}"
        codeflash_output = get_default_chrome_location(os_name) # 95.2μs -> 94.7μs (0.538% faster)

def test_massive_linux_path_checks(monkeypatch):
    # Simulate a large number of calls to os.path.exists, but only first path exists
    checked_paths = []
    def fake_exists(path):
        checked_paths.append(path)
        return path == "/usr/bin/google-chrome"
    monkeypatch.setattr(os.path, "exists", fake_exists)
    # Should return the first path
    codeflash_output = get_default_chrome_location("linux") # 1.15μs -> 1.01μs (13.3% faster)

def test_linux_performance_with_many_calls(monkeypatch):
    # Performance: simulate repeated calls to the function
    def fake_exists(path):
        return False
    monkeypatch.setattr(os.path, "exists", fake_exists)
    # Run 1000 times to check for performance issues
    for _ in range(1000):
        codeflash_output = get_default_chrome_location("linux") # 240μs -> 215μs (11.8% faster)
# 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-get_default_chrome_location-mirulto4 and push.

Codeflash Static Badge

The optimization changes the `chrome_paths` list to a tuple in the Linux branch of the function. This simple change provides an **8% speedup** by leveraging Python's more efficient tuple implementation.

**Key optimization:**
- **List to tuple conversion**: Changed `chrome_paths = ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"]` to `chrome_paths = ("/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser")`

**Why this improves performance:**
1. **Faster object creation**: Tuples are immutable and have less overhead during construction than lists
2. **Memory efficiency**: Tuples use slightly less memory per object compared to lists
3. **Reduced allocation time**: The profiler shows the tuple assignment takes ~246ns vs ~276.5ns for the list (11% faster on that line)

**Impact on workloads:**
Based on the function reference, this function is called from `setup_browser_config()` during browser configuration setup. While not in a tight loop, the optimization provides measurable gains for:
- **Linux systems**: Where the function iterates through Chrome paths using `os.path.exists()` calls
- **Test cases involving Linux**: Show 8-26% improvements in scenarios where multiple path checks are performed

**Test case performance:**
The optimization particularly benefits Linux-specific test cases:
- Cases with no existing paths: 17-18% faster
- Cases finding paths early in the sequence: 13-15% faster  
- Repeated calls on Linux systems: 10-12% faster

Since the data structure is never modified (only iterated), using a tuple is semantically appropriate and provides free performance gains with zero behavioral changes.
@codeflash-ai codeflash-ai bot requested a review from mashraf-222 December 4, 2025 19:48
@codeflash-ai codeflash-ai bot added ⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: High Optimization Quality according to Codeflash labels Dec 4, 2025
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