From 33e9a6a54e04d78f91a4787218a8eca1e5d196b8 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 8 Aug 2024 14:25:43 +0200 Subject: [PATCH] SIM110: `any()` is ~3x slower than the code it replaces (#12746) > ~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. --- .../src/rules/flake8_simplify/rules/reimplemented_builtin.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ruff_linter/src/rules/flake8_simplify/rules/reimplemented_builtin.rs b/crates/ruff_linter/src/rules/flake8_simplify/rules/reimplemented_builtin.rs index a155ed774cd37..6bcdb9c1fc232 100644 --- a/crates/ruff_linter/src/rules/flake8_simplify/rules/reimplemented_builtin.rs +++ b/crates/ruff_linter/src/rules/flake8_simplify/rules/reimplemented_builtin.rs @@ -18,8 +18,7 @@ use crate::line_width::LineWidthBuilder; /// `any` or `all`. /// /// ## Why is this bad? -/// Using a builtin function is more concise and readable. Builtins are also -/// more efficient than `for` loops. +/// Using a builtin function is more concise and readable. /// /// ## Example /// ```python