Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SIM110: any() is ~3x slower than the code it replaces #12746

Merged
merged 1 commit into from
Aug 8, 2024

Commits on Aug 8, 2024

  1. SIM110: any() is ~3x less performant than the code it replaces

    > ~Builtins are also more efficient than `for` loops.~
    
    Let's not promise performance because this code transformation does not deliver.
    
    Benchmark written by @dcbaker
    
    > `any()` seems to be about 1/3 as fast (Python 3.11.9, NixOS):
    ```python
    loop = 'abcdef'.split()
    found = 'f'
    nfound = 'g'
    
    
    def test1():
        for x in loop:
            if x == found:
                return True
        return False
    
    
    def test2():
        return any(x == found for x in loop)
    
    
    def test3():
        for x in loop:
            if x == nfound:
                return True
        return False
    
    
    def test4():
        return any(x == nfound for x in loop)
    
    if __name__ == "__main__":
        import timeit
    
        print('for loop (found)    :', timeit.timeit(test1))
        print('for loop (not found):', timeit.timeit(test3))
        print('any() (found)       :', timeit.timeit(test2))
        print('any() (not found)   :', timeit.timeit(test4))
    ```
    ```
    for loop (found)    : 0.051076093994197436
    for loop (not found): 0.04388196699437685
    any() (found)       : 0.15422860698890872
    any() (not found)   : 0.15568504799739458
    ```
    I have retested with longer lists and on multiple Python versions with similar results.
    cclauss committed Aug 8, 2024
    Configuration menu
    Copy the full SHA
    8fbf9d1 View commit details
    Browse the repository at this point in the history