nodejs / gyp-next

A fork of the GYP build system for use in the Node.js projects
BSD 3-Clause "New" or "Revised" License
125 stars 69 forks source link

misc: fix unnecessary list comprehensions #195

Closed cclauss closed 1 year ago

cclauss commented 1 year ago

An optimization recommended by ruff.

% ruff --select=C419 --fix .

Found 7 errors (7 fixed, 0 remaining).

% ruff rule C419

unnecessary-comprehension-any-all (C419)

Derived from the flake8-comprehensions linter.

Autofix is always available.

What it does

Checks for unnecessary list comprehensions passed to any and all.

Why is this bad?

any and all take any iterators, including generators. Converting a generator to a list by way of a list comprehension is unnecessary and reduces performance due to the overhead of creating the list.

For example, compare the performance of all with a list comprehension against that of a generator (~40x faster here):

In [1]: %timeit all([i for i in range(1000)])
8.14 µs ± 25.4 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)

In [2]: %timeit all(i for i in range(1000))
212 ns ± 0.892 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

Examples

any([x.id for x in bar])
all([x.id for x in bar])

Use instead:

any(x.id for x in bar)
all(x.id for x in bar)