Skip to content

Use np.add.reduce(...) instead of np.sum(...) for small performance gains #2972

@SaFE-APIOpt

Description

@SaFE-APIOpt

num_hits = np.sum(arr, axis=0) # Number of locations with each label

Hi, thank you for the clean and well-organized code!
In this line:
num_hits = np.sum(arr, axis=0)
If this appears in a performance-critical section or inside a loop, consider replacing it with:
num_hits = np.add.reduce(arr, axis=0)
np.sum(...) internally uses np.add.reduce(...), but includes additional logic (e.g., for dtype, keepdims, type promotion). If you don’t rely on those extras, using np.add.reduce(...) directly avoids that overhead and offers a small performance improvement, especially for large arrays or many iterations.

This is a micro-optimization—feel free to keep the current version if readability is preferred. Happy to open a PR if you’d like!

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