Skip to content

Replace reshape(-1,) with ravel() for faster flattening #3

Description

@SaFE-APIOpt

GARNET/hnsw.py

Line 14 in 0ce9b4d

col = neighs[:,1:].reshape(-1,)

Current code:

row = (np.repeat(idx0.reshape(-1,1), k, axis=1)).reshape(-1,)
col = neighs[:,1:].reshape(-1,)

Proposed replacement:

row = (np.repeat(idx0.reshape(-1,1), k, axis=1)).ravel()
col = neighs[:,1:].ravel()

Both reshape(-1,) and ravel() can be used to flatten arrays into 1-D.

Benchmarks show that ravel() consistently outperforms reshape(-1,), because it is optimized for flattening and avoids extra shape compatibility checks.

Additionally, ravel() is more robust: it automatically returns a view when possible and only falls back to a copy if required, while reshape(-1,) requires the array to be contiguous in memory.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions