Skip to content

Optimization Suggestion: Replace (~mask).sum() == 0 with np.all(mask) for clarity and efficiency #1

Description

@SaFE-APIOpt

if (~all_mask).sum() == 0:

Hi, thanks for the excellent codebase!

In the current logic:
if (~all_mask).sum() == 0:
the intention is to check whether all elements in all_mask are True. While this is functionally correct, it is not optimal from a performance perspective. The expression ~all_mask creates a temporary boolean array by performing a bitwise NOT, and .sum() then performs another pass to count the True values (original False values), resulting in two full traversals and unnecessary memory allocation.

This logic can be replaced with a more efficient and idiomatic expression:
if np.all(all_mask):
This avoids temporary arrays and is implemented internally in optimized C code, making it more efficient and readable.

Alternatively, if you prefer to retain the structure:
if np.count_nonzero(~all_mask) == 0:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions