Skip to content

Minor Optimization: Replace np.empty_like(a) with np.empty(a.shape, dtype=a.dtype) after known initialization #3

@SaFE-APIOpt

Description

@SaFE-APIOpt

c = np.empty_like(a)

Hi, thank you for the great work!

In the following code:

a = np.random.normal(size=shape).astype(np.float32)
b = np.random.normal(size=shape).astype(np.float32)
c = np.empty_like(a)

the third line creates an uninitialized array c with the same shape and dtype as a. While np.empty_like(a) is correct and readable, it performs internal introspection (via np.asarray) and metadata copying that are unnecessary here — both shape and dtype are already known and explicitly controlled in the previous line.

A more efficient alternative is:
c = np.empty(a.shape, dtype=a.dtype)
This avoids redundant checks and slightly improves performance, especially in high-throughput or repeatedly called initialization routines.

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