Skip to content

Optimization: Avoid np.vectorize for simple arithmetic; use direct NumPy operations instead #856

Description

@SaFE-APIOpt

f = np.vectorize(lambda x: x + 1)

Current implementation:
f = np.vectorize(lambda x: x + 1)
Recommended replacement:

def f(x):
    return x + 1

np.vectorize is often misunderstood as a performance optimization tool, but it does not provide true vectorization. Internally, it wraps a Python function in an element-wise loop, dispatching a separate Python function call for each item in the array. This approach introduces significant runtime overhead, especially for large arrays, and does not benefit from NumPy's optimized C-level operations.

In contrast, using direct NumPy expressions like x + 1 leverages low-level vectorized execution, memory-efficient loops, and SIMD acceleration. These operations are orders of magnitude faster and consume less memory.

Since the lambda function here performs a simple addition, using x + 1 directly is both semantically equivalent and far more performant. Benchmark tests consistently show 10× to 100× speedup with native NumPy expressions compared to np.vectorize.

Metadata

Metadata

Assignees

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