# numpy array access   

**URL:** <https://discuss.python.org/t/numpy-array-access/26878>\
**Category:** Python Help\
**Tags:** performance\
**Created:** [May 18, 2023, 8:19am UTC](https://discuss.python.org/t/numpy-array-access/26878 "2023-05-18T08:19:24Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![eendebakpt](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/eendebakpt/32/7552_2.png) [@eendebakpt](https://discuss.python.org/u/eendebakpt)\
**Post date:** [May 20, 2023, 6:47pm UTC](https://discuss.python.org/t/numpy-array-access/26878/5 "2023-05-20T18:47:48Z")

</div>

For both `C = A * B` and `C[:] = A * B` the product of `A` and `B` is calculated and a new object is constructed. A faster approach is to use the numpy inplace operations (assuming the array `C` can be pre-allocated). Benchmark:

```auto
import numpy as np
rng = np.random.default_rng(123)

n = 16_000_000
A = rng.random(n)
B = rng.random(n)
C = np.empty_like(A) 

%timeit C = A * B
%timeit C[:] = A * B 
%timeit np.multiply(A, B, C)

```

results in:

```auto
35.7 ms ± 173 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
47.7 ms ± 186 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
27.7 ms ± 92.9 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

```

If overwriting the contents of `A` is possible, then `A *= B` is also a fast option (about 21 ms).

---

_[View the full topic](https://discuss.python.org/t/numpy-array-access/26878)._
